Javascript关联数组在AJAX POST上变空

时间:2014-11-29 04:48:47

标签: jquery arrays ajax post

我遇到了问题。我有一个页面,其中有多个text字段具有相同的类名和不同的attribute values。我想创建一个数组,其unique键加入text field attribute值。并使用PHP将其传递到ajax页面。

我的问题是

我可以成功创建数组。但是当我尝试通过ajax发送数据时,它变为空,并且post数组不包含该值。但是当我尝试console数组时,它的值为

我的JQuery代码是

$(document).on('click', '#mybutton', function () {

    var c_array = [];
    $('.class').each(function(){

        var val1 = $(this).attr('attr1');
        var val2 = $(this).attr('attr2');
        var val3 = $(this).attr('attr3');
        var key = val1+'_'+val2+'_'+val3;
        var no = $(this).val();
        c_array[key] = no;
        alert(c_array[key]);
    });
    console.log(c_array);
    var type = 'check_cookie';
    $.ajax({
        type: 'POST',
        url: 'action.php',
        dataType: 'json',
        async: false,
        data: { type: type, c_array: c_array },
        success: function (data) {
            console.log(data);
            if (data.msg !== '' && data.msg !== null) {
                window.location = 'new.php';
            }
            else {
                alert('error');
            }
        }
    });
});

此代码有什么问题?请帮我。提前谢谢你们......

1 个答案:

答案 0 :(得分:1)

由于您已将c_array声明为数组,you should assign it numeric indices(或根据您的代码key s)。如果需要使用关联数组(即非数字索引),可以将c_array实例化为javascript对象,json数据结构或javascript对象数组。

请看一下这个fiddle或下面的堆栈代码。

// an array with numeric indices works.
// some_array has 2 entries.
var my_array = new Array()
my_array[0] = 'Test 1'
my_array[1] = 'Test 1'
var my_type = 'My Type 1'
var my_data = {type: my_type, some_array: my_array}
console.log(my_data)

// an array with non-numeric indices doesn't work.
// some_array is an empty array.
var my_array2 = new Array()
my_array2['a'] = 'Test 2'
my_array2['b'] = 'Test 2'
var my_type2 = 'My Type 2'
var my_data2 = {type: my_type2, some_array: my_array2}
console.log(my_data2)

// an array of objects work.
// some_array has 2 entries.
var my_array3 = new Array()
my_array3[0] = {'a': 'Test 3'}
my_array3[1] = {'b': 'Test 3'}
var my_type3 = 'My Type 3'
var my_data3 = {type: my_type3, some_array: my_array3}
console.log(my_data3)

// an object works.
// some_array has 2 entries.
var my_var_obj = {a: 'Test 4', b: 'Test 4'}
var my_type4 = 'My Type 4'
var my_data4 = {type: my_type4, some_array: my_var_obj}
console.log(my_data4)

// a JSON data structure works.
// some_array has 2 entries.
var my_var_obj = $.toJSON({'a': 'Test 5', 'b': 'Test 5'})
var my_type5 = 'My Type 5'
var my_data5 = {type: my_type5, some_array: my_var_obj}
console.log(my_data5)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>