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

时间:2018-05-05 18:20:19

标签: javascript jquery ajax

我通过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。我做错了什么?

2 个答案:

答案 0 :(得分:2)

当您传递手动序列化的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);
   }
 });

答案 1 :(得分:0)

因为您的数据类型。根据{{​​3}}

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: 

如果您要返回文字(“嗨”),则应指定dataType: "text"