jQuery 在来自 IE 的请求中设置 AJAX 内容类型标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9890662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set AJAX content type header in request from IE
提问by KodeKreachor
Is it possible to set the http content-type request header to 'application/json' when sending a cross domain jquery ajax http request from Internet Explorer?
从 Internet Explorer 发送跨域 jquery ajax http 请求时,是否可以将 http 内容类型请求标头设置为“application/json”?
We're trying to hit a REST WCF service that interprets the content type from the request header when formatting the response. Right now, no matter what we put in the request header it is always returning the data in XML format.
我们正在尝试访问 REST WCF 服务,该服务在格式化响应时从请求标头中解释内容类型。现在,无论我们在请求头中放什么,它总是以 XML 格式返回数据。
We've tried using the jquery.iecors.js plugin which extends the jquery ajax call to use the XDomainRequest object but that is still ignoring the content-type that is set in our jquery ajax call.
我们已经尝试使用 jquery.iecors.js 插件,它扩展了 jquery ajax 调用以使用 XDomainRequest 对象,但这仍然忽略了在我们的 jquery ajax 调用中设置的内容类型。
Here's what our ajax call looks like:
这是我们的 ajax 调用的样子:
makeGETRequest: function (requestUrl) {
return $.ajax({
type: "GET",
url: requestUrl,
contentType: 'application/json',
dataType:'json',
cache: false
});
}
回答by slashingweapon
Just pass the content-type as one of your parameters to the .ajax
method:
只需将内容类型作为参数之一传递给.ajax
方法:
var retval = jQuery.ajax({
type:'post',
url: url,
contentType: 'application/json',
data: JSON.stringify(data)
});
回答by Darin Dimitrov
Yes, you could use the contentType
parameter:
是的,您可以使用contentType
参数:
$.ajax({
url: '/someurl',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ foo: 'bar' }),
success: function(result) {
}
});
Request sent:
请求已发送:
POST /someurl HTTP/1.1
Host: example.com
Content-Length: 13
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
{"foo":"bar"}