zoukankan      html  css  js  c++  java
  • 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了!^_^

  • 相关阅读:
    LoadRunner测试结果分析
    安装LoadRunner时提示缺少vc2005_sp1_with_atl_fix_redist解决方案
    LoadRunner 11 安装及破解
    android批量文件上传(android批量图片上传)
    nginx优化配置
    redis节点管理-节点的移除
    jQuery获取表格隐藏域与ajax请求数据结合显示详情
    el表达式运算符
    EL表达式中获取list长度(JSTL函数用法)
    SQL之case when then用法(用于分类统计)
  • 原文地址:https://www.cnblogs.com/pipizhu/p/1595063.html
Copyright © 2011-2022 走看看