【问题标题】:Trying to send JSON using $.ajax, sends query string instead [duplicate]尝试使用 $.ajax 发送 JSON,而是发送查询字符串 [重复]
【发布时间】:2018-05-05 18:20:18
【问题描述】:

我正在使用以下脚本通过 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。我做错了什么?

【问题讨论】:

  • 我认为你的烧瓶代码很好。改为设置content = request.get_data(),然后您就可以确切地看到服务器正在接收的内容。
  • 你能发布你得到的打印(响应)吗?另外,请尝试 request.json。
  • 使用 content = request.json 它给了我同样的 400 错误。由于content = request.get_data(),控制台打印的内容如下:b'test=opa'。这似乎不对,事实上也不对。我刚刚在 js 中为我的 json 添加了另一个参数,服务器似乎正在接收查询字符串:b'test=opa&foo=bar'

标签: javascript jquery ajax


【解决方案1】:

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

【讨论】:

  • 是的,就是这样。必须对对象进行字符串化。
【解决方案2】:

这是因为您的数据类型。根据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"

【讨论】:

  • 这确实是我犯的一个错误,看到我只是为了拥有一个而做出响应,但它并没有解决 400 错误。我的服务器无法处理 JSON。奇怪的是,当我切换到 request.get_data() 时,我看到服务器正在接收一个查询字符串。
  • 对不起,我也忘了告诉你在使用 dataType "text" 时使用 JSON.stringify,正如 Moses 指出的那样。
猜你喜欢
  • 2012-09-23
  • 2021-04-08
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
相关资源
最近更新 更多