javascript 使用javascript从其他站点获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14537838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting data from other sites using javascript
提问by rgn
I want to to get data within divs from other websites. How can I do that using JavaScript?
我想从其他网站获取 div 中的数据。我如何使用 JavaScript 做到这一点?
回答by charlietfl
Due to cross domain restrictions you can't access the html directly using AJAX.
由于跨域限制,您无法使用 AJAX 直接访问 html。
You can however use Yahoo YQL
to select the part(s) of a page you want and have that html returned within jsonp
data.
但是,您可以使用Yahoo YQL
选择您想要的页面部分,并在jsonp
数据中返回该 html 。
Example returning list of questions on main page of stackoverflow
示例返回 stackoverflow 主页上的问题列表
var url='http://query.yahooapis.com/v1/public/yql?q=select * from html where url=\'http://stackoverflow.com/\' and xpath=\'//div[@id="question-mini-list"]//h3//a\'&format=json&callback=?';
$.getJSON( url, function(data){
$.each(data.query.results.a, function(){
$('body').append('<div><a href="http://stackoverflow.com'+this.href +'">'+this.content+'</a></div>')
})
})
DEMO: http://jsfiddle.net/NTUx5/
演示:http: //jsfiddle.net/NTUx5/
回答by hohner
You will either have to use the JSONP technique, as jungalist suggested above; or get your AJAX method to talk to a local PHP script which uses cURL:
您要么必须使用 JSONP 技术,就像上面的 jungalist 建议的那样;或者让你的 AJAX 方法与使用 cURL 的本地 PHP 脚本对话:
jQuery:
jQuery:
$('#result').load('path/to/script.php');
PHP:
PHP:
$ch = curl_init("http://example.com");
curl_exec($ch);
curl_close($ch);