问题
I need to create a JSON
ajax request
from another domain. after I think I got over the cross domain issues, here is where I stuck:
I need to add my custom "myCustomHeader
" header - that's easy from a server
, but seems to be much more complicated from the client
...
We added them
$.ajax({
type: 'POST',
data: put the results of your header request here,
url: 'http://server.com/service',
beforeSend: function (xhr) {
xhr.setRequestHeader('myCustomHeader', '1')
},
success: function(data) {
alert('success.');
}
});
This generates a preflight
header with the headers I wanted, without the values
(CSV
), but they do not appear in the header of the request
itself (as myCustomHeader=X
)...
回答1:
You can use CORS for this purpose.
Example code:
jQuery.support.cors = true;
function CrosDom_ajax(url) {
if (window.XDomainRequest
&& $.browser.msie
&& $.browser.version < 10) {
xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function () {
alert(xdr.responseText);
};
xdr.open("get", url);
xdr.send();
}
}
else {
$.ajax({
url: url,
success: function (response) {
},
error: function (data) {
}
});
}
}
Also you need to Write the following code in server side, to allow cross domain access
Response.AppendHeader("Access-Control-Allow-Origin", "*");
来源:https://stackoverflow.com/questions/15090797/cross-domain-jquery-ajax-request-with-custom-headers-and-request-body-as-json-st