最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - creating a associative arrayhash in javascript - Stack Overflow

programmeradmin2浏览0评论

I have a form with different groups of checks boxes and trying to pass all the selected values into an array then pass that data into a ajax request.

$('#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
})

I get a wizard.searchArray like :

   [0] = {'acc_1' : 'vase'},
   [1] = {'acc_3' : 'ceramic'}

I need to create a key-value as I use the key to work out which part of the filtering to use.

The problem

When I do the ajax request, from firebug I see the request as :

/wizard-demo/?undefined=undefined&undefined=undefined

I have a form with different groups of checks boxes and trying to pass all the selected values into an array then pass that data into a ajax request.

$('#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
})

I get a wizard.searchArray like :

   [0] = {'acc_1' : 'vase'},
   [1] = {'acc_3' : 'ceramic'}

I need to create a key-value as I use the key to work out which part of the filtering to use.

The problem

When I do the ajax request, from firebug I see the request as :

/wizard-demo/?undefined=undefined&undefined=undefined

Share Improve this question asked Sep 8, 2010 at 9:43 thiswayupthiswayup 2,0678 gold badges32 silver badges52 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

In this case just push add the properties to the obj and use it directly, that's the pair that'll get serialized property when used as the data property, like this:

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

$.ajax({
   data : obj
});

Though this is backwards from a normal <form> submission, if that's what you want it's this instead:

obj[this.name] = this.value;

If you wanted to send the entire form, there's a much shorter/built-in .serialize() method for this:

$.ajax({
   data : $("#accessoriesForm").serialize()
});
发布评论

评论列表(0)

  1. 暂无评论