javascript - 在 cordova/ratchet 移动应用程序中发出 AJAX 请求时遇到困难

标签 javascript php jquery ajax cordova

我在让 Cordova 项目中的 AJAX 请求正常工作时遇到困难。

$.ajax({
    url: "https://mydevserver/REST.php?method=mobileGetData",
    success: function(result){
        alert("successful ajax");
    },
    error: function(xhr, ajaxOptions, thrownError){
        alert("error");
        alert("xhr.status");
        alert(thrownError);
    }
});

带有此代码的警报中打印的状态代码为 0,并带有空错误消息。我认为这很奇怪,并进行了一些研究,结果表明答案是跨站点脚本的限制,可以通过 CORS 来解决。我尝试了第一个答案here并将以下内容放入我的 head 标记中。

<script src="js/jquery-2.1.1.min.js"></script>
<script>
    $(document).bind("mobileinit", function(){
        $.support.cors = true;
        $.mobile.allowCrossDomainPages = true;
    });
</script>
<script type="text/javascript" src="cordova.js"></script>

但是这对运行代码的结果没有影响。在同一个答案中,建议将 cache: false 添加到 ajax 选项以及 async: false 中,因此我将它们添加到我的代码中。结果是,我的请求得到的状态代码不是 0,而是状态代码 404。此时,我检查了 URL 是否拼写错误,并尝试将 URL 更改为 example.com,这也给出了 404 的状态代码。

接下来我尝试了该答案的第三个建议,即使用纯 JavaScript 的 XMLHttpRequest 对象。

var req = new XMLHttpRequest();
req.open("POST", "https://mydevserver/REST.php?method=mobileGetData", true);

req.onreadystatechange = function() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            alert("successful ajax");
        }else{
            alert("Error: " + req.status);
        }
    }
};
req.send(null);

这种方法还产生了状态代码 0。最后一些 more research据透露,答案可能是 JSONP,这是浏览器内置的跨站点脚本限制的一种解决方法。根据他的教程,我更改了移动应用程序中的 REST 函数和 AJAX 调用。

REST.php

if($_GET['method'] == "mobileGetData"){
    $output = array(array("Name" => "Jesse", "NumEntries" => "1")); //the end result of my actual code. I can't really put in the actual SQL queries and whatnot for security reasons
    $output = $_GET['jsonp_callback'] . "(" . json_encode($output) . ");";
    echo $output
}

AJAX

$.ajax({
    dataType: 'jsonp',
    data: 'method=mobileGetData',
    jsonp: 'jsonp_callback',
    url: "https://mydevserver/REST.php",
    success: function(result){
        alert("successful ajax");
    },
    error: function(xhr, ajaxOptions, thrownError){
        alert("error");
        alert(xhr.status);
        alert(thrownError);
    }
});

不幸的是,这次尝试没有产生状态代码 0(尽管这次尝试有一条错误消息“error”,而其他所有尝试都有一条空白错误消息)。我不确定还可以尝试什么,或者我是否搞砸了我尝试过的其他方法之一。谁能告诉我我哪里可能出错了?对于摘要和上下文,以下是当前完整的 head 标记内容:

<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />

    <!-- Set the viewport settings to prevent scaling -->
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, target-densitydpi=device-dpi" />

    <!-- Makes your prototype chrome-less once bookmarked to your phone's home screen -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <title>RealtyShout: Subscriptions</title>
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <link rel="stylesheet" href="css/ratchet.css">
    <meta name="msapplication-tap-highlight" content="no" />
    <script src="js/jquery-2.1.1.min.js"></script>
    <script>
        $(document).bind("mobileinit", function(){
            $.support.cors = true;
            $.mobile.allowCrossDomainPages = true;
        });
    </script>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script src="js/ratchet.js"></script>
    <script type="text/javascript">
        app.initialize();
        $(function(){
            alert("https://mydevserver/REST.php?method=mobileGetData"));
            $.ajax({
                dataType: 'jsonp',
                data: 'method=mobileGetSubscriptionsByNotifier',
                jsonp: 'jsonp_callback',
                url: "https://mydevserver/REST.php",
                success: function(result){
                    alert("successful request");
                },
                error: function(xhr, ajaxOptions, thrownError){
                    alert("error");
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        });
    </script>
    <style>
        /*Stops the text from being in all caps*/
        body * {
            text-transform: none;    
        }
    </style>
</head>

为了编译我的代码,我使用 cordova CLI,如下所示:

cordova build ios
cordova emulate iOS

编辑:根据 @frank 的建议,我将 URL 更改为 ip.jsontest.com 以查看它是否真的是我的开发服务器,并再次返回状态代码 0。然而,后来我尝试了 http://ip.jsontest.com状态代码为 200,错误代码为 Error: jQuery 21107076784837990999_1409318004872 was not calledMy research表明这是由于服务器未配置为构建 JSONP 响应而导致的。

最佳答案

假设您正在正确构建 JSON/JSONP 响应(您可以通过网络浏览器和相同的 JS 代码进行测试),请确保您在响应中设置正确的 header (REST.php):

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

Access-Control-Allow-Origin 将允许您从原始服务器外部请求数据。我猜这就是你遇到的问题。此外,错误的响应编码可能会导致 Ajax 调用失败。

同样,您应该能够在浏览器的控制台中调试错误(如果有),只需进行应用程序尝试运行的相同调用即可。仔细检查响应是否有效。

关于javascript - 在 cordova/ratchet 移动应用程序中发出 AJAX 请求时遇到困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25555611/

相关文章:

javascript - 通过 Ajax 调用从 DataTable 中删除行

javascript - 值得麻烦地提交 package-lock.json 吗?

javascript - WebRTC 从不触发 IceCandidate

javascript - AngularJS/Javascript 下拉菜单 "onchange"功能不起作用

php - 存储来自 2 个表 Laravel 的外键值

javascript - 为什么这个段落元素会阻止 jQuery 工作?

javascript - 我不知道如何修复此代码

javascript - 在wordpress中动态添加和删除html表中的行

php - 从 friend 和所有者的帖子中选择 INNER JOIN

javascript - 如何将reCaptcha v2与JS和PHP表单集成?