1. 程式人生 > >jQuery的ajax 方法提交多個數組問題

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('新增失敗')
                }
            }
        });
    }