简体   繁体   中英

How do you get content from another domain with .load()?

Requesting data from any location on my domain with .load() (or any jQuery ajax functions) works just fine.

Trying to access a URL in a different domain doesn't work though. How do you do it? The other domain also happens to be mine.

I read about a trick you can do with PHP and making a proxy that gets the content, then you use jQuery's ajax functions, on that php location on your server, but that's still using jQuery ajax on your own server so that doesn't count.

Is there a good plugin?

EDIT: I found a very nice plugin for jQuery that allows you to request content from other pages using any of the jQuery function in just the same way you would a normal ajax request in your own domain.

The post: http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

The plugin: https://github.com/jamespadolsey/jQuery-Plugins/tree/master/cross-domain-ajax/

This is because of the cross-domain policy, which, in sort, means that using a client-side script (aka javascript...) you cannot request data from another domain. Lucky for us, this restriction does not exist in most server-side scripts.

So...

Javascript:

$("#google-html").load("google-html.php");

PHP in "google-html.php":

echo file_get_contents("http://www.google.com/");

would work.

Different domains = different servers as far as your browser is concerned. Either use JSONP to do the request or use PHP to proxy. You can use jQuery.ajax() to do a cross-domain JSONP request.

One really easy workaround is to use Yahoo's YQL service, which can retrieve content from any external site.

I've successfully done this on a few sites following this example which uses just JavaScript and YQL. http://icant.co.uk/articles/crossdomain-ajax-with-jquery/using-yql.html

This example is a part of a blog post which outlines a few other solutions as well. http://www.wait-till-i.com/2010/01/10/loading-external-content-with-ajax-using-jquery-and-yql/

I know of another solution which works. It does not require that you alter JQuery. It does require that you can stand up an ASP page in your domain. I have used this method myself.

1) Create a proxy.asp page like the one on this page http://www.itbsllc.com/zip/proxyscripts.html

2) You can then do a JQuery load function and feed it proxy.asp?url=....... there is an example on that link of how exactly to format it. Anyway, you feed the foreign page URL and your desired mime type as get variables to your local proxy.asp page. The two mime types I have used are text/html and image/jpg.

Note, if your target page has images with relative source links those probably won't load. I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM