How to load website HTML using jquery

寵の児 提交于 2020-01-03 12:28:56

问题


How can I load some website in my java-script so that I can parse it? I want to get Html of e.g. www.google.com and I want to select all the tags in it using jquery.


回答1:


You can't as jquery doesn't allow you to load external resources, unless in the page you want to parse is present the header:

header('Access-Control-Allow-Origin: http://thesitewhereyourjscodeishosted');

If you can't set it, you could use PHP:

<script>
var website = <?php echo file_get_contents("http://websitetoload"); ?>;
</script>



回答2:


Due to browser security restrictions, Ajax requests are subjected to the same origin policy; the request can not be successfully retrieve data from a different domain, subdomain, port, or protocol.

But you can build a script on your server that requests that content or can use a proxy, then use jQuery ajax to hit the script on your server.

Working Fiddle

It's just proxying a request through Yahoo's servers and getting back a JSONP response even if the requested server doesn't support JSONP.

HTML:

<div id="example"></div>

JavaScript

$('#example').load('http://wikipedia.org');

Here is a similar question like yours Ways to circumvent the same-origin policy?

good luck!




回答3:


You can easily set up node server that gets the content of the page, and then make an ajax request to your server and get whatever data you need.



来源:https://stackoverflow.com/questions/26184630/how-to-load-website-html-using-jquery

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