最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to specify an external website for XMLHTTPRequest - Stack Overflow

programmeradmin2浏览0评论

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/test.php" looks for a file on the current server, and ".php" justseems to outright fail.

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.

Share Improve this question edited May 4, 2009 at 19:43 Sergey Ilinsky 31.5k9 gold badges56 silver badges56 bronze badges asked May 4, 2009 at 16:53 JohnJohn 1
  • To clarify your question, it doesn't matter where the JS file is hosted. What matters is where the PAGE referencing your JS file is hosted. That is what determines same-originness. – EricLaw Commented Jul 24, 2009 at 5:26
Add a comment  | 

5 Answers 5

Reset to default 7

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.

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

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.

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?

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: *
发布评论

评论列表(0)

  1. 暂无评论