如何从另一个域获取数据(json 格式)?
我的问题是:我想从以下位置获取数据:http://pin-codes.in/api/pincode/400001/
我尝试过使用 CORS,但没有成功。
我的控制台是:
获取http://pin-codes.in/api/pincode/400001 [HTTP/1.1 200 OK 780ms]
错误 错误
我的客户端脚本代码:
$(document).ready(function() {
$("#get_data_btn").click(function() {
var data_path = "http://pin-codes.in/api/pincode/400001";
$.getJSON(data_path, null)
.done(function(data) {
console.log("Success: " + data.status);
})
.fail(function(jqxhr, textStatus, error) {
console.log("Error Error");
});
});
});
最佳答案
您可能不拥有其他域,对吧?
完全没问题。别介意反对者,在计算中一切都是好的!
只需在您的服务器上使用简单的代理或查看 YQL .
这个简单的查询将起作用:
select * from json where url="http://pin-codes.in/api/pincode/400001/ "
只需测试 this link (绕过跨域安全公牛$#!7)。
它将获取您请求的数据,作为包装在回调函数 cbfunc
中的普通纯 json(无 jsonp)数据。
看看this question获取更多信息(我在 SO 上做了很多 yql 抓取答案)。
更新:
这是一个粗略的 fiddle 演示整个过程:所以你输入一个网址,单击“获取”并观看神奇的发生:http://jsfiddle.net/NbLYE/
function getJSON(url) { //quick and dirty
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(script);
}
function cbfunc(json){ //the callback function
if(json.query.count){
var data=json.query.results.json;
// do your work here, like for example:
//document.getElementById('output').innerHTML=data.toSource();
} else {
alert('Error: nothing found'); return false;
}
}
function fetch(url){ //scrape the url you'd want
var yql="select * " +
" from json" +
" where url='" + url + "';";
yql="http://query.yahooapis.com/v1/public/yql?q=" +
encodeURIComponent(yql) +
"&format=json" +
"&callback=cbfunc";
getJSON(yql);
}
这应该可以帮助您入门(并因为它简单而受到激励)。
希望这会有所帮助!
关于javascript - 从另一个域获取数据(json格式),无需jsonp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20510336/