如何将JSON数据发送到服务器

嗯,这是故事:

我有一些数据需要发送到服务器,但他们应该首先变成JSON dataType。

我做了这样的ajax电话:

$.ajax({ url: url, // the url I want to post to. type: 'POST', contenttype:'application/json; charset=utf-8', beforeSend: //some HTTP basic auth stuff data: { name:'test', key:'foo', key2:'bar' }, dataType:'JSON' }); 

基本上我期待我发送给服务器的数据是:

 [name:test,key:foo,key2:bar] 

但我得到的是:

 name=test&key=foo&key2=bar 

我错过了什么? 如何将这些数据转换为JSON?

  var data = {'bob':'foo','paul':'dog'}; $.ajax({ url: url, type: 'POST', contentType:'application/json', data: JSON.stringify(data), dataType:'json' }); 

/** 添加 **/

如果您需要执行某些操作,则上述操作对服务器的响应无效,然后在服务器响应时将调用回调。

  var data = {'bob':'foo','paul':'dog'}; $.ajax({ url: url, type: 'POST', contentType:'application/json', data: JSON.stringify(data), dataType:'json', success: function(data){ //On ajax success do this alert(data); }, error: function(xhr, ajaxOptions, thrownError) { //On error do this if (xhr.status == 200) { alert(ajaxOptions); } else { alert(xhr.status); alert(thrownError); } } }); 

我遇到了同样的问题。 您不能将对象作为“数据”发送,您需要对对象进行字符串化。 请尝试使用此对象进行字符串化:

 $.ajax({ url: url, type: 'POST', contentType:'application/json', data: '{ name:"test", key:"foo", key2:"bar" }', dataType:'json' }); 

试试这个: http : //www.abeautifulsite.net/blog/2008/05/postjson-for-jquery/

它短得多:

 $.post(url, data, function(response) { // Do something with the response }, 'json'); 

此外,necesary可以创建一个参数并使用JSON.stringify分配值

 .... data: "jsonString="+JSON.stringify(data), ... 

我同意数据必须转换为JSON字符串,不仅要与dataTypecontentType设置一致,更重要的是要满足服务器要求。

 data: JSON.stringify(data), dataType:'json' 
 dataType: 'json',