问题描述
跨域Ajax POST请求工作完全正常的网页浏览器,包括在手机上的浏览器,但使用内置的本地应用程序无法正常工作的PhoneGap
Cross-domain AJAX POST request works perfectly fine on web browsers including browsers on mobile phones, but doesn't work for native applications built using Phonegap
我创建了一个登录表单,用户必须输入他们的登录凭据,然后他们由托管在Heroku上,并返回JSON {成功:真}服务器进行验证
如果有效凭证进入。
I have created a login form that users have to enter their login credentials, then they are verified by the server that is hosted on heroku and returns json {"success":true}
if valid credentials are entered.
我的Ajax脚本:
$.ajax({
type: "POST",
url: "http://domain.com/public/auth/app-login",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
data: {identity: <username from form>, password: <password from form>},
crossDomain: true,
cache: false,
success: function(data) {
obj = JSON.parse(data);
if (obj && obj.success === true) {
window.location.href = 'home.html';
}
},
error: function(e) {
alert('Error: ' + e.message);
}
});
要解决这一问题而采取的步骤:
Steps taken to resolve this issue:
- 域名白名单 - config.xml中
- Domain whitelisting - config.xml
&LT;获得原产地=http://domain.com/public/auth/app-login/&GT;
<access origin="http://domain.com/public/auth/app-login" />
&LT;获得原产地=*/&GT;
<access origin="*" />
- 告诉jQuery的允许跨域
$ .support.cors = TRUE;
要么jQuery.support.cors = TRUE;
$.support.cors = true;
ORjQuery.support.cors = true;
- 禁用缓存
缓存:假
任何帮助是AP preciated。
Any help is appreciated.
推荐答案
确定。如果index.html的地方,那么你可以调用阿贾克斯任何主机,不需要启用客户端或服务器CORS。您删除:
Ok. If index.html in local then you can call ajax any hosts, not need enable CORS in client or server. You remove:
$.support.cors = true; OR jQuery.support.cors = true;
和
<access origin="http://domain.com/public/auth/app-login" />
这多余的,只使用:
It redundant, only use:
<access origin="*" />
您需要检查并添加在AndroidManifest.xml中:
You need check and add in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
添加更多的权限,如果你需要的应用程序。最后,调用阿贾克斯在$(文件)。就绪():
Add more permission if your app required. Finally, call ajax inside $(document).ready():
$.ajax({
type: "POST",
url: "http://domain.com/public/auth/app-login",
dataType: "json",
data: {identity: <username from form>, password: <password from form>},
success: function(data) {
obj = JSON.parse(data);
if (obj && obj.success === true) {
window.location.href = 'home.html';
}
},
error: function(e) {
alert('Error: ' + e.message);
}
});
这篇关于PhoneGap的跨域Ajax POST请求不工作在Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!