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
813 views
in Technique[技术] by (71.8m points)

cordova - AJAX Request from Phonegap Android fails

I have been working on this for the last two days, and looking at a lot of other suggestions. Yes I can get this simple ajax request to work from within a phonegap application, both on the android emulator and on an actual android phone.

My phonegap version is (using phonegap -v) 3.0.0-0.14.3

The code I'm using is:

var url = 'http://www.thomas-bayer.com/sqlrest/CUSTOMER';
    return $.ajax({
        type: "GET",
        url: url,
        timeout: 60 * 1000
    }).done(function (data) {
        alert('hey');
    }).fail(function (a, b, c) {
        console.log(b + '|' + c);
    });

The result I'm getting in the log is just:

error| at file:///android_asset/www/js/index.js:62

I added the settings to the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

and I have the following in Config.xml

<param name="android-package" value="org.apache.cordova.core.NetworkManager" />

When I check navigator.connection.type I get 3G on the emulator and wifi on the physical phone.

Any idea what else could go wrong?

UPDATE: If I log the JSON in the first parameter of the failing function I get:

{"readyState":4,"status":404,"statusText":"error"}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You should whitelist the domain in order for your AJAX calls to work.

Add this line to config file -:

<access origin="*" />

Phonegap's default policy blocks all network access unless specified otherwise. The above line will disable this security restriction. You can also be more specific in allowing only certain domains to bypass this security feature by including the domain name in the config file like so

<access origin="http://yourdomain" />

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

...