尝试使用$ .ajax发送JSON,发送查询字符串而不是

我通过ajax使用以下脚本发送JSON:

var dat = {"test":"opa"}; console.log(dat); $.ajax({ contentType: "application/json", method: "POST", url: "/test", dataType: "json", data: dat, success:function(res){ console.log(res); } }); 

但我的服务器收到一个查询字符串,如test=opa&foo=bar 。 我究竟做错了什么?

当您传递手动序列化的JSON字符串时,jquery将自动URLEncode您的数据。

我建议你JSON.stringify它

 $.ajax({ contentType: "application/json", method: "POST", url: "/test", dataType: "json", data: JSON.stringify(dat), success:function(res){ console.log(res); } }); 

这是因为你的数据类型。 根据http://api.jquery.com/jQuery.ajax/

 dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are: 

如果要返回文本(“Hi”),则应指定dataType: "text"