jQuery: query a $.get() returned string

2019-03-04 10:52发布

How can i query a string i get via $.get? for example, i want form google only the body html:

$.get("www.google.com", function(data){
var body = $("body", data).html(); //This doesnt work
});

Is it even possible? thanks

2条回答
成全新的幸福
2楼-- · 2019-03-04 11:27

Nope, jQuery can't directly access the DOM of a page that was loaded via an XmlHttpRequest. In order to do this, you would have to use an HTML parser written in JavaScript, like the one that John Resig wrote. It's still a much harder task than you were probably expecting though.

查看更多
萌系小妹纸
3楼-- · 2019-03-04 11:43

One thing is that this wont work because you need a HTML parser. The other is that unless you are doing this on www.google.com this wont work because of the same origin policy. There are ways to circumvent this, most popular is JSONP, but this can be done manually as well, without using the jsonp method defined by jQuery.

Edit:
If you don't want to go through the problems of getting content from a different domain in your JavaScript, an alternative method would be to use your server be it, PHP, .NET ect to fetch the remote page and then return it the the JavaScript using AJAX. This will ofcause be a little more time consuming than doing it directly in the js, as you are doing 2 requests instead of one. However, depending on your server tools, you might have an easier time parsing the html instead of doing that in the js, so you more easily can get the stuff you want to your page.

查看更多
登录 后发表回答