jQuery有$ .getJSON()函数,用于从其他域加载json文件,如下所示:
$.getJSON('http://somesite.com/file.js', function(output) {
// do stuff with the json data
});
我想知道我是否可以对来自其他域的xml文件做同样的事情,或者我是否必须使用服务器端语言?
这是我要加载的xml文档:
http://google.com/complete/search?output=toolbar&q=microsoft
答案 0 :(得分:2)
我同意@viyancs,简单地说如果你想获得其他域的xml,有一个跨域限制,解决这个的方法是创建一个代理,所以请求过程是:
1。使用$ .ajax来请求您的代理(使用您想要访问的真实xml网址)。
2。您的代理会检索xml网址内容。
3。您的代理将内容返回到$ .ajax调用。
有关详细信息,请查看:http://developer.yahoo.com/javascript/howto-proxy.html
BTW:为什么你不必为JSON做这个?这是一种名为JSONP的技术。答案 1 :(得分:0)
你可以试试这个
$.ajax({
type: "GET",
dataType: "xml",
url:"localhost/grab.php",
success: function(){
//to do when success
}
});
1)使服务作为代理从url获取内容 在grab.php代码中的示例:
<?php
$url = 'http://google.com/complete/search?output=toolbar&q=microsoft';
$parsing = parse_url($url);
$scheme = $parsing[scheme];
$baseurl = basename($url);
$strbase =$baseurl;
$finalUri = $scheme .'://' .$strbase;
$handle = fopen($finalUri, "r",true);
// If there is something, read and return
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
&GT;
答案 2 :(得分:0)
如果你真的没有能力使用具有缓存的代理(这是正确的礼仪),你可以使用像YQL as a JSONP proxy service这样的东西。如果没有API密钥,您最终会达到限制。
// query: select * from xml where url='http://google.com/complete/search?output=toolbar&q=microsoft'
var xml_url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fgoogle.com%2Fcomplete%2Fsearch%3Foutput%3Dtoolbar%26q%3Dmicrosoft'&diagnostics=true"
$.get(xml_url,function(xml){ console.log(xml); });