如何将JSON数据发送到服务器 [英] How can I send JSON data to server

查看:494
本文介绍了如何将JSON数据发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,这是故事:

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

I have some data need to send to server, but they should turned into JSON dataType first.

我做了这样的ajax电话:

I made such ajax call:

    $.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'
});

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

basically I'm expecting the data I send to server was:

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

但我得到的是:

name=test&key=foo&key2=bar

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

What did I missing? How can I get those data into JSON?

推荐答案

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

/ **已添加** /

/** Added **/

如果您需要执行某些操作,上面的内容对服务器的响应没有任何作用,那么当服务器响应时将调用回调。

The above does not do anything with the response from the server if you need to do something then a callback will be called when the server has responded.

 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);
        }
    }
 });

这篇关于如何将JSON数据发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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