jquery ajax里面的datetype设成json时,提交不了数据的问题

前天在使用jQuery作练习时发现的,$.ajax(properties)其中传递参数data的问题.根据文档说是:(Object|String) data - 要发送到服务器的数据。如果还不是一个字符串,就自动轮换为一个查询字符串。即附加到GET请求的url后面的字符串.但是我给data赋值一个json对象数据,然而,它不能转换成"查询字符串".

类似源码:

前台代码:
  <script type="text/javascript">
$(document).ready(function() {
            $("#Text1").blur(function() {
                var strjson=jQuery.param({'name':'china','pwd':'200009'});
                $.ajax({
                    type: "POST", 
                   // contentType: "application/json", //这个就别设置了,要不非出错不可,因为我不了解。有知道的留言,谢谢
                    url: "reg.ashx",
                    data: strjson,  //这个地方为json的话  需要经过这一步要不不好使(后台获取不到):
                                     // var strjson=jQuery.param({'name':'chinacxyy','pwd':'200009'});
                                     //我也不知道怎么回事 看一下jquery.js中$.ajax()和$.post()的定义,就知道了
                    dataType: "json",
                    success: function(result) {
                       alert("OK"+result.msg);
                    },
                   
              error : function(){
                  alert("错了");
              }
                });
            });
        });
    </script>
后台代码:

  public class reg : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            response.ContentType = "application/json";
            string namename = request.Params["name"];
            response.Write("{msg:'"+namename+"',result:'ddddd'}");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


    在调试过程中发现,服务器端获取就是一个空数组,由此说明json_data在post时并没有转换成字符串.当然,如果在此使用$.post(url, params, callback)其中,params指定为json_data,则完全正常.

    于是,我查看了下jquery.js中$.ajax()和$.post()的定义,发现$.post()过程,对params进行jQuery.param(data)加工(json转换成字符串的过程).所以,问题由此解决了,如果想在$.ajax中的data使用json对象,只要先jQuery.param(data)下,就万事OK了!^_^

原文地址:https://www.cnblogs.com/pipizhu/p/1595063.html