javascript 当我的数据类型为“JSON”时,为什么我的 Ajax 请求会发送“内容类型:应用程序/x-www-form-urlencoded”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23857707/
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
Why is my Ajax request sending "Content-Type: application/x-www-form-urlencoded" when I have dataType: "JSON"?
提问by packetie
When I am using the following to respond to a button click, it it called (verified by using the console.log()), however, the http request it generated has the header "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n". Shouldn't it be json?
当我使用以下内容响应按钮单击时,它调用(通过使用 console.log() 验证),但是,它生成的 http 请求具有标题“Content-Type: application/x-www-form -urlencoded;字符集=UTF-8\r\n"。不应该是json吗?
I am using google chrome 34.0.1847.132 on Ubuntu. Jquery version 1.8.3.
我在 Ubuntu 上使用谷歌浏览器 34.0.1847.132。jQuery 版本 1.8.3。
Thanks in advance!
提前致谢!
function action (mode) {
console.log("action called with mode " + mode);
$.ajax({
type: "POST",
url: '/saas.php',
data: {
action: (mode == 1)? "start" : "stop"
},
dataType: "json",
success: function(data) {
//alert(data);
if (data.msg != null) {
alert(data.msg);
} else {
if (mode == 1) {
document.getElementById('createLoadGen').innerHTML = 'creating loadGen...';
setTimeout(checkStatus, 1000);
}
}
}
});
if (mode == 2) {
document.getElementById('createLoadGen').innerHTML = '<button onclick="action(1)" >create LoadGen</button>';
document.getElementById('deleteLoadGen').style.display = 'none'
}
}
回答by Quentin
Not generally. The Content-Type header in the requestdescribes the content in the requestbody, not the type of content that is expected in the response(describing the expected response format is the job of the Accept
header).
一般不会。请求中的Content-Type 标头描述了请求正文中的内容,而不是响应中预期的内容类型(描述预期的响应格式是Accept
标头的工作)。
By default, jQuery will encode the data using the standard encoding used by HTML forms.
默认情况下,jQuery 将使用 HTML 表单使用的标准编码对数据进行编码。
Now, it mightbe that the server is expecting the request to be formatted as JSON, in which case you would need to make the following modifications to the jQuery call:
现在,服务器可能希望将请求格式化为 JSON,在这种情况下,您需要对 jQuery 调用进行以下修改:
- Say that you are sending JSON
- Encode the content you are sending as JSON instead of letting jQuery encode it itself
- 假设您正在发送 JSON
- 将您发送的内容编码为 JSON,而不是让 jQuery 自行编码
Such:
这样的:
data: JSON.stringify({
action: (mode == 1)? "start" : "stop"
}),
contentType: "application/json",
sass.php
will then have to parse the JSON requestinstead of letting PHP do it invisibly in the background and just plucking the data out of $_POST
.
sass.php
然后将不得不解析 JSON 请求,而不是让 PHP 在后台不可见地执行它,而只是从$_POST
.