我想从其他网站获取div中的数据。 我怎么能用JavaScript做到这一点?
答案 0 :(得分:8)
由于跨域限制,您无法使用AJAX直接访问html。
但是,您可以使用Yahoo YQL
选择所需页面的部分,并在jsonp
数据中返回该html。
示例返回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>')
})
})
答案 1 :(得分:-1)
你要么必须use the JSONP technique,正如上面提到的jungalist;或者让你的AJAX方法与使用cURL的本地PHP脚本对话:
<强> jQuery的:强>
$('#result').load('path/to/script.php');
<强> PHP:强>
$ch = curl_init("http://example.com");
curl_exec($ch);
curl_close($ch);