get html of external url in jquery

2020-01-25 11:46发布

How can i get external URL's HTML using jquery?

标签: jquery html url
6条回答
来,给爷笑一个
2楼-- · 2020-01-25 11:53

You need jquery $.get

http://api.jquery.com/jQuery.get/

Example: Alert out the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).

$.get("test.cgi", { name: "John", time: "2pm" },
   function(data){
     alert("Data Loaded: " + data);
   });

Edit: this only works if your page is on the same domain.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-01-25 11:53

You could use $.ajax or $.get to make a call to a URL on your own domain and then use whatever server-side language you are using to retrieve the HTML and then return it.

It's two HTTP requests instead of one but it'll get around your problem.

You could also cache the external sites HTML in your backend code so that a request from the Javascript does not always result in two HTTP requests - of course, all depends on how often the HTML you want to grab will change.

A slight twist on the above would be to have a background task running on your server that retrieves the external HTMl every X seconds and saves it locally. Requests to your domain from your JS just pick up the latest copy from your server. That means your JS request isn't slowed down by waiting for another external HTTP request.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-01-25 12:04

On it's simplest form - You can't.

You are bound with same origin policy.

查看更多
闹够了就滚
5楼-- · 2020-01-25 12:13

All common Browsers do not allows Javasript Calls to access any Pages with another (sub)Domain because of the Same Origin Policy. The only way to work around that is to set up some kind of "proxy" on your own server (for example an php Script) that runs under the same Domain, gets the Information you want from a third source and prints them out.

查看更多
兄弟一词,经得起流年.
6楼-- · 2020-01-25 12:15

You could add a PHP or any other server side language to your site that could act as a proxy for your script to fetch the page html.

You could then call your server side proxy with the url using Ajax which would return you the HTMl of that page.

查看更多
狗以群分
7楼-- · 2020-01-25 12:17

The short answer is you can't, because AJAX requests are limited to the same (sub)domain and port by the Same Origin Policy.

The same restrictions apply to iframe elements: You can't create an iframe pointing to the external page, and grab its HTML from there.

The usual way is to use a server-side script (written e.g. in PHP) that serves as a proxy: It fetches the external site's content and serves it back to JavaScript. It will have to run on the same domain as the page.

Obviously, using this solution, relative references to URLs, images, stylesheets and such (e.g. ../images/image.gif) will no longer work, as they areout of context on your page. Whether that is a problem in your situation is impossible to tell. One workaround for that may be using a <base> tag.

查看更多
登录 后发表回答