Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

jquery - Phonegap Cross-domain AJAX POST Request not working on Android

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

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.

My Ajax script:

$.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:

<access origin="http://domain.com/public/auth/app-login" />

<access origin="*" />

  • Telling jQuery to allow cross-domain

$.support.cors = true; OR jQuery.support.cors = true;

  • Disable caching cache: false

Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

And:

<access origin="http://domain.com/public/auth/app-login" />

It redundant, only use:

<access origin="*" />

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);
   }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...