我正试图在Windows Phone 7.5上使用以下代码与jQuery。每次我尝试对xml进行ajax请求时,错误处理程序都会返回"Access is Denied"。不幸的是,JSONP在这种情况下不起作用,因为我需要的数据只有XML。我不知道该如何解决这个问题。
编辑:我应该指出,代码在Chrome和Safari上运行良好。然而,我没有一台Windows机器可以在IE上测试。编辑2:在IE9上测试,出现相同错误。
javascript:
function loadData(index) {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.ajax({
url: "http://foo.bar/some.xml",
dataType: "xml",
success: parseData,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
};
php代理获取xml
<?php
header('Content-type: text/xml');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
$intme = date('YmdHis');
$start = $_GET['ind'];
$url = "http://some.data.source/data.xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>
我不知道普通JQuery怎么样,但当我使用phonegap时,我遇到了同样的问题,并写了这个:
在发出AJAX请求之前,您必须允许跨域请求和核心支持,通过设置:
jQuery.support.cors = true;
$.mobile.allowCrossDomainPages = true;
这些必须在特定的电话间隙功能"DeviceReady"中设置,例如:
document.addEventListener('deviceready', function () {
jQuery.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.ajax({
url: "www/about.txt",
dataType: 'text'
}).done(function (result) {
alert(result);
});
});
2.2.url
制作面向WindowsPhone8的应用程序,在AJAX请求中,您必须指定资源的完整路径,例如:网址:"www/about.txt",
制作面向WindowsPhone8的应用程序,在AJAX请求中,您不能指定资源的完整路径,例如:url:"about.txt",
2.3.源文件扩展名
请小心使用未知的扩展文件,如模板扩展名*.tpl或类似文件。有时AJAX不喜欢它们,我建议使用简单的*.txt和*.html扩展。
3.getJSON
不知怎的$.getJSON在Windows Phone上不起作用,例如:
$.getJSON('www/jsonfiles/jsonfile.txt',
function(data, status, jqXHR) {
if(status == "success") {
alert(data);
}
});
您可以将其替换为AJAX请求,如下所示:
$.ajax({
url: 'www/jsonfiles/jsonfile.txt',
dataType: 'text'
}).done(function (result) {
Alert( JSON.parse(result));
});