无法发送带有cordova的ajax请求

时间:2016-07-14 11:32:44

标签: javascript jquery ajax cordova

我启动了新项目并添加了请求代码。我的js文件看起来像这样:

(function () {
"use strict";

document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );

function onDeviceReady() {

    $.ajax({
        type: "GET",
        url: "http://api.vk.com/method/database.getCountries?v=5.5&need_all=0",
        crossDomain: true,
        success: function (response) {
            alert('Works!');
        },
        error: function (data) {
            console.log(data);
            alert('Not working!');
        }
    });

    // Handle the Cordova pause and resume events
    document.addEventListener( 'pause', onPause.bind( this ), false );
    document.addEventListener( 'resume', onResume.bind( this ), false );

    // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
    var parentElement = document.getElementById('deviceready');
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');
    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');
};

function onPause() {
    // TODO: This application has been suspended. Save application state here.
};

function onResume() {
    // TODO: This application has been reactivated. Restore application state here.
};
})();

但它根本不起作用。它总是返回“不工作”。我尝试过其他方式发送请求,但总是出错。 请帮助!

1 个答案:

答案 0 :(得分:0)

Cordova 5.0默认阻止外部http请求。

尝试将cordova-plugin-whitelist添加到您的项目中。

重建您的应用仍会问题仍然存在。请执行以下操作之一:

1)在你的回应服务中设置跟随牧人:

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

2)将此行添加到配置文件 - :

<access origin="*" />

3)除白名单外,请确保cors标志为true以启用跨源资源共享。

$.support.cors=true;

4)您可以关注生成请求的this $ .getJSON而不是ajax。

希望它会对你有所帮助。