0

Included below is the code that I am trying to use to display the HTML contents of another page. I am unable to get the code to work and am receiving an error each time. What am I missing here?

$.ajax({
    url: 'http://www.msn.com',  
    type: 'GET',
    dataType : "text/html",
    success: function (result) {
        alert('success');
        alert(result);
    },
    error: function() { 
       alert('error');
}
});
4

6 回答 6

3

You cannot do a cross-domain AJAX request (unless the servers are specifically set up for it).

The best you can do is call a PHP script on your server, which in turn gets the HTML from the other server and sends it back to your page.

于 2012-07-06T17:31:25.990 回答
3

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

Script and JSONP requests are not subject to the same origin policy restrictions.

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

于 2012-07-06T17:32:34.890 回答
2

You can only make ajax requests to your own domain. Point it to your own pages and your success function will be called.

于 2012-07-06T17:31:25.537 回答
1

In Chrome, open up Web Inspector (e.g. right-click, Inspect Element) and go to the Console tab, then run that code. You will then actually get to see the cross-domain scripting security error you are triggering.

于 2012-07-06T17:31:48.473 回答
1

If you indeed intended to do a Cross-Domain AJAX request and you're looking to retrieve a HTML response you may want to check out this article by James Podolosky, where he discusses piping these sort of requests through YQL and provides a plugin to automate this by overriding the jQuery.ajax function, allowing you to use it as you expected here.

于 2012-07-06T17:36:58.147 回答
1

If you're fine using an external API, you can use YQL (but it's not perfect).

Check this fiddle and you'll see it working. Perhaps it's not for you, just throwing it out there.

于 2012-07-06T17:39:45.073 回答