jQuery: query a $.get() returned string

不想你离开。 提交于 2019-12-04 06:15:36

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1508095/jquery-query-a-get-returned-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!