我无法在我的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
中,因此我将其添加到我的代码中。结果是,我的请求获得了状态代码404,而不是状态代码0。在这一点上,我检查了我没有以某种方式拼错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(尽管这种尝试有一个错误消息“错误”,其中每次其他尝试都有一个空白的错误消息)。我不知道还有什么可以尝试,或者我可能搞砸了我试过的其他方法之一。谁能告诉我哪里可能出错了?对于摘要和上下文,这里是完整的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 called
。 My research显示,这是在服务器未配置为构建JSONP响应时引起的。
假设您正在构建正确的JSON / JSONP响应(可以从Web浏览器和相同的JS代码进行测试),请确保在响应中设置正确的标头(REST.php):
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
Access-Control-Allow-Origin允许您从原始服务器外部请求数据。我想你遇到的问题是哪个。此外,使用错误的响应编码可能会导致Ajax调用失败。
同样,你应该能够在浏览器的控制台中调试你的错误(如果有的话),只是让你的应用尝试运行同一个调用。仔细检查响应是否有效。
在看了here后,我尝试使用$.getJSON
使其工作并设法得到一个很好的回应。
$.getJSON("http://devserver/REST.php?callback=?", "method=mobileGetData", function(response, status, xhr){
for(var key in response[0]){
alert(key + ": " + response[0][key]);
}
);