简体   繁体   中英

Cross-domain $.ajax request is not working

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');
}
});

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.

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/

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

In Chrome, open up Web Inspector (eg 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.

如果您确实打算执行跨域AJAX请求,并且希望检索HTML响应,则可以查看James Podolosky的这篇文章 ,他在本文中讨论了通过YQL传递此类请求并提供了一个自动化插件通过重写jQuery.ajax函数,可以按预期使用它。

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.

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