问题
I need to POST data to a server in a different domain. That server is using SSL and expects the data to be in the form of a JSON string. I am attempting to do this from javascript.
I create the data and use JSON.stringify() to get it into the correct format. Then I send it as follows:
var url = "https://api.postageapp.com/v.1.0/send_message.json";
http=new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("Connection", "close");
// create the data in a data structure named post_data
var JSONText = JSON.stringify(post_data);
http.send(JSONText);
Doing a packet trace I see my client do a handshake with the server but then twice the server replies with "Encrypted alert" including the last time it sends a packet back. The browser debugger always shows a 405 - Method Now Allowed error.
What am I missing to get this to work? When they try it within their domain it runs fine.
回答1:
You need server to return a HTTP Header like that:
header('Access-Control-Allow-Origin: *');
Live example: Making cross domain JavaScript requests using XMLHttpRequest or XDomainRequest
回答2:
You cannot do a cross domain post like that.
Alternative is to use Server side proxy (read this link for a nice explanation as to why you can't do that) or iframe approach.
回答3:
Strictly speaking it should not be possible (due to security issues) however using a workaround called JSONP you can achieve this with a RESTful web service.
See the link below. http://en.wikipedia.org/wiki/JSONP
MS has some code you can download somewhere on the internet with specific bindings the code is called.
- JSONPBehaviour.cs
- JSONPBindingElement.cs
- JSONPBindingExtension.cs
- JSONPEncoderFactory.cs
来源:https://stackoverflow.com/questions/7098662/still-confused-about-using-xmlhttprequest-cross-domain