在javascript中创建关联数组/哈希

thi*_*yup 2 javascript ajax jquery

我有一个包含不同检查框组的表单,并尝试将所有选定的值传递给一个数组,然后将该数据传递给ajax请求.

$('#accessoriesOptions input').each(function(index, value){
    if($(this).attr('checked') ){
        var newItem =[];
        var obj = {};
        obj[$(this).attr('value')] = $(this).attr('name'); //I have an hash table with the key-value
        wizard.searchArray.push(obj);
    }            
})

$.ajax({
   data : wizard.searchArray
})
Run Code Online (Sandbox Code Playgroud)

我得到一个wizard.searchArray像:

   [0] = {'acc_1' : 'vase'},
   [1] = {'acc_3' : 'ceramic'}
Run Code Online (Sandbox Code Playgroud)

我需要创建一个键值,因为我使用键来计算要使用的过滤部分.

问题

当我执行ajax请求时,从firebug我看到请求为:

/向导演示/?未定义未定义=&未定义未定义=

Nic*_*ver 5

在这种情况下,只需将属性添加到obj并直接使用它,即当用作属性时将获得序列化属性的对data,如下所示:

var obj = {};
$('#accessoriesOptions input').each(function(index, value){
    if(this.checked){
        obj[this.value] = this.name;
    }            
})

$.ajax({
   data : obj
});
Run Code Online (Sandbox Code Playgroud)

虽然这是正常<form>提交的倒退,如果这是你想要的,那就是:

obj[this.name] = this.value;
Run Code Online (Sandbox Code Playgroud)

如果你想发送整个表单,那么有一个更短/内置的.serialize()方法:

$.ajax({
   data : $("#accessoriesForm").serialize()
});
Run Code Online (Sandbox Code Playgroud)