使用javascript从其他网站获取数据

时间:2013-01-26 14:26:38

标签: javascript jquery

我想从其他网站获取div中的数据。 我怎么能用JavaScript做到这一点?

2 个答案:

答案 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>')          
     })
})

DEMO:http://jsfiddle.net/NTUx5/

YQL文档:http://developer.yahoo.com/yql/guide/index.html

答案 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);