使用JQuery发布JSON

Jus*_*tin 4 jquery json

试图让JQuery将JSON发布到服务器:

$.ajax({  
  url: "/path/to/url",  
  type: "POST",  
  dataType: "json",  
  contentType: "json",  
  data: {"foo": "bar"},  
  success: function(){              
    alert("success :-)");  
  },  
  error: function(){  
    alert("fail :-(");  
  }  
});  
Run Code Online (Sandbox Code Playgroud)

问题是数据出现在服务器上"foo=bar"而不是所需的数据"{\"foo\":\"bar\"}.

我认为指定dataType或contentType参数可以做到这一点,但没有.

有人知道正确的ajax配置吗?[或者在发布之前将'data'参数序列化为JSON的方法?]

谢谢!

Dar*_*rov 10

你可以使用json2.js:

data: JSON.stringify({"foo": "bar"})
Run Code Online (Sandbox Code Playgroud)