问题
Here is my situation:
I have a Webserver machine, Client machine, and a third machine running some program that listens for XMLHttpRequests.
Client accesses the Webserver from the Client machine, makes some changes, and then clicks on'Save'. At this point, data is being sent back to the Webserver and to the Third machine. All of this is being done using Javascript and XMLHttpRequest object.
The post to the Webserver works fine, however post to the Third machine does not work, since it had a different IP/domain.
How can I make this work? Client machine -> Third machine does not work, because its on a different domain Webserver machine -> Third machine does not work, because of firewall issues
Any ideas are greatly appreciated!
回答1:
What you're running into is the Same origin policy, not firewall issues.
If the machines share a top-level domain, you can set their document.domain properties to match:
Two sites sharing a common top-level domain may opt to communicate despite failing the "same host" check by mutually setting their respective document.domain DOM property to the same qualified, right-hand fragment of their current host name.
Otherwise, you may need to setup your first host to proxy the request to the other host.
回答2:
You can implement CORS (Cross-Origin Resource Sharing) on your server.
The current versions of the major desktop browsers have supported it for a while, Opera and Explorer 10 being the last ones to add support.
I'm not sure how widely supported CORS is across mobile browsers at this time though.
回答3:
You could also use the iframe hack. An iframe hosted by the second domain can be rendered in a page hosted by the first domain, and the window object for the iframe will be accessible from the parent page's context.
回答4:
Another option (which is admittedly a bit techie) is to use YQL if the data isn't sensitive. You can use YQL & JSON-P in order to fetch data from other domains as well.
来源:https://stackoverflow.com/questions/3144093/cross-domain-xmlhttprequest