How to specify an external website for XMLHTTPRequ

2020-07-18 03:08发布

问题:

When using an XMLHTTPRequest in javascript, I want to send it to an external website, rather than the one where the .js file is hosted. To send it to test.php on the current server, I would use

request.open("POST", "test.php", true);

but for the second arguemnt, how do I send it to another website. "example.com/test.php" looks for a file on the current server, and "http://example.com/test.php" justseems to outright fail.

回答1:

You can't for security reasons. See the same origin policy for JavaScript.

There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended.

The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted.



回答2:

This sounds like a bad case of Same Origin Policy, my friend :)



回答3:

You can't (for the most part) use XmlHttpRequest to get data from an external website. What you can do, however, is dynamically create a SCRIPT tag and reference an external address. jQuery wraps this functionally as part of its ajax handling.



回答4:

Indeed you can. Not in any browser although.

In Internet Explorer 8.0 there is XDomainRequest, an object enabling cross-domain requests. You would need to properly handle request made with this object on server by sending Access-Control-Allow-Origin header first with "*" or requester domain name.

Since you are doing some hacky things anyway, why not trying to use it on IE8 first?



回答5:

If you have control over the server, you can use this header in the HTTP reply, although it may not work with all browsers.

Access-Control-Allow-Origin: *