gpt4 book ai didi

javascript - 不用jsonp从另一个域获取数据(json格式)

转载 作者:行者123 更新时间:2023-11-29 17:12:55 25 4
gpt4 key购买 nike

如何从另一个域获取数据(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 (绕过跨域安全 bull$#!7)。
它将获取您请求的数据作为包装在回调函数 cbfunc 中的普通纯 json(无 jsonp)数据。

看看this question了解更多信息(我在 SO 上做了很多 yql 抓取答案)。


更新:

这是一个演示整个过程的粗略 fiddle :所以你输入一个 url,单击 fetch 并观看魔术发生: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 - 不用jsonp从另一个域获取数据(json格式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20510336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com