尝试使用$ .ajax发送JSON,而是发送查询字符串 [英] Trying to send JSON using $.ajax, sends query string instead

查看:100
本文介绍了尝试使用$ .ajax发送JSON,而是发送查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am sending JSON via ajax with the following script:

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

But my server receives a query string such as test=opa&foo=bar. What am I doing wrong?

推荐答案

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

When you pass a manually-serialized JSON string, jquery will automatically URLEncode your data.

我建议你JSON.stringify它

I suggest you JSON.stringify it

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

这篇关于尝试使用$ .ajax发送JSON,而是发送查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆