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

javascript - How to pass dynamic amount of data in jQuery ajax post - Stack Overflow

programmeradmin3浏览0评论
$.ajax({
  url: '<?=parseLink("modules/Contacts/output/output.php")?>',
  data: { 
    $('.contacts-block-input-text').each(function(){
      id: $(this).attr('id'),
      value: $(this).val()
    })
  },
  type: 'post',
  success: function(result){
    $('.resultMessage').text(result)
  }
})

So there will be dynamic amount of input fields and I need to gather all the contacts-block-input-text values and pass them in the data field somehow. How could I do this? The given example doesn't work.

$.ajax({
  url: '<?=parseLink("modules/Contacts/output/output.php")?>',
  data: { 
    $('.contacts-block-input-text').each(function(){
      id: $(this).attr('id'),
      value: $(this).val()
    })
  },
  type: 'post',
  success: function(result){
    $('.resultMessage').text(result)
  }
})

So there will be dynamic amount of input fields and I need to gather all the contacts-block-input-text values and pass them in the data field somehow. How could I do this? The given example doesn't work.

Share Improve this question asked Oct 2, 2015 at 9:54 XeenXeen 7,01317 gold badges69 silver badges113 bronze badges 2
  • data accepts a string or an object. I'm not sure exactly what you're trying to achieve with your usage of each() in there. Can you give some details about what data your output.php is expecting to receive. – Rory McCrossan Commented Oct 2, 2015 at 9:56
  • 1 Why don't you just serialize these inputs? Set a name attribute to each ones if none already set then use data: $('.contacts-block-input-text').serialize(), – A. Wolff Commented Oct 2, 2015 at 9:59
Add a ment  | 

3 Answers 3

Reset to default 7

You have to build an array, collecting your input data:

var myData = [];
$('.contacts-block-input-text').each(function(){
  myData.push({
      id: $(this).attr('id'),
      value: $(this).val()
  });
});

Then you can use myData to pass it to the ajax call.

$.ajax({
  url: '<?=parseLink("modules/Contacts/output/output.php")?>',
  data: myData,
  type: 'post',
  success: function(result){
    $('.resultMessage').text(result)
  }
});

You can simply iterate through your jQuery array, bine the data object, and then pass it to AJAX call:

var d = [];
$(".contacts-block-input-text").each(function() {
    d.push({ id: this.id, value: this.value });
});    

$.ajax({
    data: d
// ...

You may also use $.map() to generate a data object and pass it over to the ajax method, as below.

var myData = $('.contacts-block-input-text').map(function() {
    return { 'id': this.id, 'value': this.value };
}).get();

$.ajax({
    url: '....',
    data: myData,
    //and so on... 
});
发布评论

评论列表(0)

  1. 暂无评论