【问题标题】:Phonegap AJAX request undefinedPhonegap AJAX 请求未定义
【发布时间】:2016-05-18 02:24:26
【问题描述】:

我对来自网页的cordova/phonegap/ajax 请求有疑问。由于该应用程序正在与在手机上运行的phonegap 开发者应用程序一起使用并完美地发送ajax requests。我认为这与permissions/plugins 或其他东西有关。但是当我使用cordova 安装应用程序时,它不会发送任何内容,整个ajax request 会返回:

readyState: 0
responseText: undefined
status: 0
text status: error
error

在config.xml我已经设置了

<access origin="*" />

在AndroidManifest.xml 我已经设置了

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

这是ajax request 本身

$.ajax({
    method: "GET",
    crossDomain: true,
    dataType: 'json',
    url: 'http://mywebsite.com/projectname/index.php',
    data: { x: userLocation.latitude, y: userLocation.longitude },
    success: function(data){  
        alert("Success: "+ data);
    },
    error: function(xhr, textStatus, err) { 
        alert("readyState: " + xhr.readyState);
        alert("responseText: "+ xhr.responseText);
        alert("status: " + xhr.status);
        alert("text status: " + textStatus);
        alert("error: " + err);
    }
});

将cordova.js 包含到项目中:

<script type="text/javascript" src="cordova.js"></script>
<script src='js/jquery.js'></script>
<script>
    $(document).bind('mobileinit', function () {
        $.mobile.changePage.defaults.changeHash = false;
        $.mobile.hashListeningEnabled = false;
        $.mobile.pushStateEnabled = false;
    });
</script> 
<script ...here comes js file where ajax is called out

设置这些也不起作用

$.support.cors = true;
$.mobile.allowCrossDomainPages = true;

【问题讨论】:

    标签: javascript android jquery ajax cordova


    【解决方案1】:

    如果您运行的是 Cordova 5 或更高版本,则您的 HTML 中需要一个内容安全策略元标记,以便向外部服务器发出 Ajax 请求。如果您从较旧的 Cordova 版本开始并升级到 5 或 6,则您的 index.html 中可能没有其中之一。如果您从 CLI 启动了一个新的 Cordova 5 或 6 应用程序,那么模板“Cordova is Ready”应用程序将拥有一个,但提供的示例程序不允许向其他服务器发出 Ajax 请求,除非您明确配置它。

    您可以在 index.html 中添加类似的内容,以允许任何地方的 Ajax 请求:

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src http://api.fixer.io">
    

    也可以在content-security-policy.com 或我的博文here 上查看如何配置connect-src,以配置更紧密的CSP 以满足您的需求。

    此外,您可能希望使用 Cordova“deviceready”事件而不是“mobileinit”,因为您可能在 Cordova 完全准备好之前过早地进行 Ajax 调用,因此请在以下 (onDeviceReady) 回调中调用 Ajax:

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

    或在调用之后执行的某些内容中,表明 Cordova 已准备就绪。

    【讨论】:

      【解决方案2】:

      显然我花了足够长的时间才弄明白,所以我是这样工作的: 首先我从项目中卸载了所有插件,然后删除了文件夹platforms/android。在 CMD 中输入:

      cordova platform add android
      

      然后再次安装必要的插件。 现在它正在工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-20
        • 1970-01-01
        • 2013-07-05
        • 2013-11-03
        • 2016-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多