天天看点

jQuery的ajax 方法提交多个数组问题

function addUser(){

        $.ajax({
            url:'UserAdd',
            data:{list1:arr1,list2:arr2},
            type:'post',
            success:function(msg){
                if(msg=='1'){
                    console.log('添加成功');
                }else{
                    console.log('添加失败')
                }
            }
        });
    }
           

在网上查找资料之后了解到ajax post之前会用因为jQuery需要调用jQuery.param序列化参数,我们来看下jquery源码

//在ajax()方法中,对json类型的数据进行了$.param()处理
if ( s.data && s.processData && typeof s.data !== "string" ) {
    s.data = jQuery.param( s.data, s.traditional );
}

//param方法中
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
        // Serialize the form elements
        jQuery.each( a, function() {
            add( this.name, this.value );
        });

    } else {
        // If traditional, encode the "old" way (the way 1.3.2 or older
        // did it), otherwise encode params recursively.
        for ( prefix in a ) {
            buildParams( prefix, a[ prefix ], traditional, add );
        }
    }
           

找到原因之后就好办啦

首先,traditional为false,我们可以通过设置traditional 为true阻止深度序列化

function addUser(){

        $.ajax({
            url:'UserAdd',
            data:{list1:arr1,list2:arr2},
            type:'post',
            traditional:true,    //这里必须设置
            success:function(msg){
                if(msg=='1'){
                    console.log('添加成功');
                }else{
                    console.log('添加失败')
                }
            }
        });
    }
           

继续阅读