Phonegap跨域AJAX POST请求不适用于Android [英] Phonegap Cross-domain AJAX POST Request not working on Android
问题描述
跨域 AJAX POST 请求在 Web 浏览器(包括手机浏览器)上运行良好,但不适用于使用 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 {"success":true}
输入.
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);
}
});
为解决此问题所采取的步骤:
- 域白名单 - config.xml
- Domain whitelisting - config.xml
<代码><access origin="http://domain.com/public/auth/app-login"/>
<代码><access origin="*"/>
- 告诉 jQuery 允许跨域
<代码>$.support.cors = true;或者<代码>jQuery.support.cors = true;
- 禁用缓存
cache: false
感谢任何帮助.
推荐答案
好的.如果 index.html 在本地,那么你可以在任何主机上调用 ajax,不需要在客户端或服务器中启用 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" />
多余,只用:
<access origin="*" />
您需要在 AndroidManifest.xml 中检查并添加:
You need check and add in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
如果您的应用需要,请添加更多权限.最后,在 $(document).ready() 中调用ajax:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!