关于Jquery中ajax方法data参数用法的总结

data 发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。

示例:
$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
});
这里data后面跟的参数可以用二种表式:一种是普通url传参的写法一样,还有一种就是写在json数组里,
上面示例data部分也可以这样写:data: {name:"John",location:"Boston"}。这二个用法有什么区别?
今天在开发中发现二者用法的细微差别。第一种我们用url传参,参数里面如果加带"&"这个符号的话,可能参数接收不到或不完整,如“ data: "name=John&location=Boston",”,
如果name的值是"john&smith"这样写可能就会有问题,我们可以用JS里面的encodeURIComponent()方法进行转义,
但如果用data: {name:"John",location:"Boston"}这种方式写的话就不需要进行转义,如果转义的话,接收的将是转义后的字符串

转自:
http://www.cnblogs.com/tim190/archive/2010/10/20/1856523.html

但是,我这里碰到一个data参数传递了,后面字符串传递的方式好像有问题?后来发现是contentType: "application/json",这个参数的问题,它规定了传递给后台方法的参数必须是json格式既——{键:'值',键:'值'}
function StatisticsPlot(type, condition, contymd) {
    try {
        $.ajax({
            contentType: "application/json",
            url: "/Statistics/StatisticsPlot",
            data: "{type:'" + type + "',condition:'" + condition + "',contymd:'" + contymd + "'}",//'type='+type+'&condition='+condition+'&contymd='+contymd,
            type: "POST",
            async: true,
            dataType: "json",
            success: function (json) {
                if (json != null) {
                    var plotList = json;
                    var strs;
                    var ticks1;
                    var ssy;
                    var lb;
                    if (type == "MONTH") {
                        strs = new Array(12);
                        for (var m = 0; m < plotList.length; m++) {
                            var plotItem = plotList[m];
                            var ss = plotItem.Flag.split("-");
                            ssy = ss[0] + "年月份盈余统计";
                            strs[ss[1] - 1] = plotItem.ProfitMoney;
                        }
                        //alert(strs);
                        //1,2,3,4,5,6,7 ,8    ,9  ,10,11,12
                        //strs = [, , , , , , 30, 50.00, 105.00, , , ];
                        ticks1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
                        lb = "月份";
                    }
                    if (type == "QUARTER") {
                        strs = new Array(4);
                        for (var m = 0; m < plotList.length; m++) {
                            var plotItem = plotList[m];
                            var ss = plotItem.Flag.split("-");
                            ssy = ss[0] + "年季度盈余统计";
                            strs[ss[1] - 1] = plotItem.ProfitMoney;
                        }
                        //alert(strs);
                        //1,2,3,4,5,6,7 ,8    ,9  ,10,11,12
                        //strs = [, , , , , , 30, 50.00, 105.00, , , ];
                        ticks1 = ["1", "2", "3", "4"];
                        lb = "季度";
                    }
                    if (type == "YEAR") {
                        strs = new Array(plotList.length);
                        ticks1 = new Array(plotList.length);
                        for (var m = 0; m < plotList.length; m++) {
                            var plotItem = plotList[m];
                            ssy = "盈余年度统计";
                            ticks1[m] = plotItem.Flag;
                            strs[m] = plotItem.ProfitMoney;
                        }
                        //ticks1 = ["1", "2", "3", "4"];
                        lb = "年份";
                    }
                    if (type == "DAY") {
                        var sl = condition.split("-");
                        var d = new Date(sl[0], sl[1], 0);
                        var anum = parseInt(d.getDate());
                        strs = new Array(anum);
                        ticks1 = new Array(anum);
                        for (var k = 0; k < anum; k++) {
                            ticks1[k] = k + 1;
                        }
                        ssy = condition + "月盈余统计";
                        lb = "日";
                        for (var m = 0; m < plotList.length; m++) {
                            var plotItem = plotList[m];
                            var ss = plotItem.Flag.split("-");
                            strs[ss[2] - 1] = plotItem.ProfitMoney;
                        }
                    }
                    //   var plot1 = $.jqplot('chart1', [strs],
                    //     {
                    //          seriesDefaults: {
                    //           renderer: $.jqplot.BarRenderer,
                    //           pointLabels: { show: true },
                    //           rendererOptions: {
                    //            fillToZero: true //已0为坐标,负数向下
                    //             }
                    //        },
                    //        title: ssy,
                    //        series: [{ color: '#CC0100'}],
                    //        axes: {
                    //        xaxis: {
                    //        renderer: $.jqplot.CategoryAxisRenderer,
                    //        ticks: ticks1,
                    //        label: lb
                    //        },
                    //        yaxis: {
                    //          numberTicks: 10
                    //            }
                    //         }
                    //   });
                    var plot2 = $.jqplot('chart1', [strs], {
                        seriesDefaults: {
                            renderer: $.jqplot.canvasTextRenderer,
                            //pointLabels: { show: true },
                            rendererOptions: {
                                fillToZero: true //已0为坐标,负数向下
                            }
                        },
                        title: ssy,
                        //        legend: {
                        //            labels: ticks1,
                        //            renderer: $.jqplot.EnhancedLegendRenderer,
                        //            show: true,
                        //            location: 'ne',
                        //            placement: 'outside',
                        //            rendererOptions: {
                        //                seriesToggleReplot: { resetAxes: true }
                        //            }
                        //        },
                        axes: {
                            xaxis: {
                                renderer: $.jqplot.CategoryAxisRenderer,
                                rendererOptions: {
                                    tickRenderer: $.jqplot.CanvasAxisTickRenderer
                                },
                                ticks: ticks1,
                                label: lb,
                                tickOptions: {
                                    angle: -30
                                }
                            },
                            yaxis: {
                            //pad: 1.2
                        }
                    },
                    highlighter: {
                        show: true
                    },
                    zoom: {
                        show: true
                    },
                    cursor: {
                        show: true,
                        zoom: true,
                        //showTooltip: false
                    }
                });
            }
        },
        error: function (err) { throw err; }
    });
} catch (er) {
    throw er;
}

另外一个ajax里面beforeSend:Success:error比较全的例子:
        $.ajax({
            url: "/Account/AccountInpourRecordsPart",
            data: { orderid: orderid, username: username, beginTime: beginTime, endTime: endTime, status: status, moneytype: moneytype, pageindex: pIndex },
            type: "POST",
            beforeSend: function () {
                var loadingtr = $("<tbody class='ModelListShow'><tr><td colspan='10'>&nbsp;&nbsp;" + Account.messages.jiazaizhong + "...</td></tr></tbody>");
                if ($("div#SearchUserInfoList .ModelListShow")) {
                    $("div#SearchUserInfoList .ModelListShow").replaceWith(loadingtr);
                }
            },
            success: function (json) {
                if (LoginOrPermis(json) == false) {
                    return false;
                }
                if ($("div#SearchUserInfoList .ModelListShow")) {
                    $("div#SearchUserInfoList .ModelListShow").replaceWith(json);
                    $("#TxtOrderId").val(orderid);
                    $("#HidUserName").val(username);
                    $("#TxtBeginTime").val(beginTime);
                    $("#TxtEndTime").val(endTime);
                    $("#Status").val(status);
                    $("#MoneyType").val(moneytype);
                    IsInintLoad = true;
                }
                if (IsInintLoad) {
                    $("div#SearchUserInfoList p#RecordsPagerNumList").pagination(parseInt($("#UsersInpourRecordsListCount").val()), {
                        num_edge_entries: 2,
                        num_display_entries: 5,
                        items_per_page: pSize,
                        current_page: pIndex,
                        link_to: "javascript:void();",
                        callback: AccountInpourOnPageChanged
                    });
                    IsInintLoad = false;
                }
            },
            error: function (err) {
                var loadingtr = $("<tbody class='ModelListShow'><tr><td colspan='10'>&nbsp;&nbsp;" + Account.messages.zanwushuju + "</td></tr></tbody>");
                if ($("div#SearchUserInfoList .ModelListShow")) {
                    $("div#SearchUserInfoList .ModelListShow").replaceWith(loadingtr);
                }
            }
        });


JQuery中$.ajax()方法参数详解

(2010-08-02 15:26:36)
标签:

jquery

ajax

each

it

分类: JQuery

url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址。

type: 要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和

      delete也可以使用,但仅部分浏览器支持。

timeout: 要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设

         置。

async:要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。

       如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等

       待请求完成才可以执行。

cache:要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false)。

       设置为false将不会从浏览器缓存中加载请求信息。

data: 要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格

      式。get请求中将附加在url后。防止这种自动转换,可以查看processData选项。对象必须为key/value格

      式,例如{foo1:"bar1",foo2:"bar2"}转换为&foo1=bar1&foo2=bar2。如果是数组,JQuery将自动为不同

      值对应同一个名称。例如{foo:["bar1","bar2"]}转换为&foo=bar1&foo=bar2。

dataType: 要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime

          信息返回responseXML或responseText,并作为回调函数参数传递。

          可用的类型如下:

          xml:返回XML文档,可用JQuery处理。

          html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。

          script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求

                  时(不在同一个域下),所有post请求都将转为get请求。

          json:返回JSON数据。

          jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个

                “?”为正确的函数名,以执行回调函数。

          text:返回纯文本字符串。

beforeSend:要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义

            HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参

            数。

            function(XMLHttpRequest){

               this;   //调用本次ajax请求时传递的options参数

            }

complete:要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。

          参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。

          function(XMLHttpRequest, textStatus){

             this;    //调用本次ajax请求时传递的options参数

          }

success:要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。

         (1)由服务器返回,并根据dataType参数进行处理后的数据。

         (2)描述状态的字符串。

         function(data, textStatus){

            //data可能是xmlDoc、jsonObj、html、text等等

            this;  //调用本次ajax请求时传递的options参数

error:要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错

       误信息、捕获的错误对象(可选)。

       ajax事件函数如下:

       function(XMLHttpRequest, textStatus, errorThrown){

          //通常情况下textStatus和errorThrown只有其中一个包含信息

          this;   //调用本次ajax请求时传递的options参数

       }

contentType:要求为String类型的参数,当发送信息至服务器时,内容编码类型默认

             为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。

dataFilter:要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。

            提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的

            dataType参数。函数返回的值将由jQuery进一步处理。

            function(data, type){

                //返回处理后的数据

                return data;

            }

global:要求为Boolean类型的参数,默认为true。表示是否触发全局ajax事件。设置为false将不会触发全局

        ajax事件,ajaxStart或ajaxStop可用于控制各种ajax事件。

ifModified:要求为Boolean类型的参数,默认为false。仅在服务器数据改变时获取新数据。

            服务器数据改变判断的依据是Last-Modified头信息。默认值是false,即忽略头信息。

jsonp:要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。

       该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,例如

       {jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。

username:要求为String类型的参数,用于响应HTTP访问认证请求的用户名。

password:要求为String类型的参数,用于响应HTTP访问认证请求的密码。

processData:要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度

             来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM

             树信息或者其他不希望转换的信息,请设置为false。

scriptCharset:要求为String类型的参数,只有当请求时dataType为"jsonp"或者"script",并且type是GET时

               才会用于强制修改字符集(charset)。通常在本地和远程的内容编码不同时使用。

案例代码:

$(function(){

    $('#send').click(function(){

         $.ajax({

             type: "GET",

             url: "test.json",

             data: {username:$("#username").val(), content:$("#content").val()},

             dataType: "json",

             success: function(data){

                         $('#resText').empty();   //清空resText里面的所有内容

                         var html = ''; 

                         $.each(data, function(commentIndex, comment){

                               html += '<div class="comment"><h6>' + comment['username']

                                         + ':</h6><p class="para"' + comment['content']

                                         + '</p></div>';

                         });

                         $('#resText').html(html);

                      }

         });

    });

});

顺便说一下$.each()函数:

$.each()函数不同于JQuery对象的each()方法,它是一个全局函数,不操作JQuery对象,而是以一个数组或者对象作为第1个参数,以一个回调函数作为第2个参数。回调函数拥有两个参数:第1个为对象的成员或数组的索引,第2个为对应变量或内容。

原文地址:https://www.cnblogs.com/BluceLee/p/3752790.html