Cross origin request blocked

2020-04-08 14:19发布

I want to retrieve json data from an other website so I tried to do a simple crossdomain request. I ran this index.php file on Wamp :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" manifest="manifest.appcache">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MySite</title>
<script type="text/javascript">
    function getXDomainRequest() {
        var xdr = null;

        if (window.XDomainRequest) {
            xdr = new XDomainRequest();
        } else if (window.XMLHttpRequest) {
            xdr = new XMLHttpRequest({mozSystem: true});
        } else {
            alert("Your browser does not support AJAX");
        }

        return xdr;
    }
    function sendData() {
        var xdr = getXDomainRequest();
        xdr.onload = function() {
            alert(xdr.responseText);
        }

        xdr.open("GET", "http://example.com");
        xdr.send();
    }
</script>
</head>
<body>
<p>
        <input type="button" onclick="sendData();" value="Retrieve" />
</p>
</body>
</html>

But I get an error saying that cross origin request has been blocked. I'm pretty new to js and this is the first time I try to use a web API in js so I might have completly missed something here...

Thanks a lot.

1条回答
老娘就宠你
2楼-- · 2020-04-08 14:31

Javascript requests can only be cross-domain under certain circumstance. Below is a summary of a few techniques and work-arounds.

  1. If the source has JSONP available, you can circumvent cross-domain restrictions. http://www.sitepoint.com/jsonp-examples/

  2. Unlikely, but if the source has a origin policy, than you could do the cross domain request. Seeing as you are getting the error, I doubt the source has this policy. If I recall, this is not supported by all browsers...

  3. If I recall, there are some iFrame methods (I would call them hacks) to transport the data. Not optimal at best.

  4. If all else fails, you can cache the JSON file with PHP and store it on your server. No longer is it cross domain.

More details can be found at Ways to circumvent the same-origin policy

If you are attempting to pull it from a public API, than it is very likely that they have JSONP available. If they do not, it is likely that they don't want you to pull the data every time (they don't want to foot the bandwidth bill), but rather would prefer you cache it with PHP as necessary.

查看更多
登录 后发表回答