Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...