使用 ajax 将可变数量的变量定义为 post

define variable number of vars to post with ajax

我有一些动态定义的标签输入,我希望 post 与以下 ajax 标签的变量数量相同: 仅部分或全部 $('#tag_x').val() 将被定义

  $.ajax({
    url:'/ajax/defineTags/',
    type:'post',
    data:{
      tag_1:$('#tag_1').val(),
      tag_2:$('#tag_2').val(),
      tag_3:$('#tag_3').val(),
      tag_4:$('#tag_4').val(),
      tag_x:$('#tag_x').val(),
      tag_20:$('#tag_20').val()
    }
  }).always(function(response){
    console.log(response);
  });

我的问题是,我是否使用序列化?这不是一个标准的形式。 如果是这样,请解释如何?我希望我已经说清楚了。

谢谢!

你可以使用

var data = $('input[id^="tag_"]').serialize();

DEMO

添加要序列化的数据

var data = $('input[id^="tag"]').serialize();
var Add_Data = data+'&id='+$('#tags-id').text();

DEMO

更复杂的

var data = $('input[id^="tag"]').serialize();
$('span[id^="tags"]').each(function(){
    var ThisText = $(this).text();
    var ThisId = $(this).attr('id');
    var add_Data = ThisId+'='+ThisText;
    data = data+'&'+ add_Data;
});
$('div').text(data); 

DEMO

并在 ajax 中使用

data: data

关于 .serialize()

你应该知道的事

The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as , , and : $( "input, textarea, select" ).serialize();

and the output should be something like this

single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1

关于 .serializeArray()

你应该知道的事

The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls. The controls can be of several types:

the output

[ { name: "a", value: "1" }, { name: "b", value: "2" }, { name: "c", value: "3" }, { name: "d", value: "4" }, { name: "e", value: "5" } ]

您可以使用 .serializeArray()

var data_arr = $('[id^=#tag_]').serializeArray();
$.ajax({
    url:'/ajax/defineTags/',
    type:'post',
    data:data_arr
  }).always(function(response){
    console.log(response);
  });

一个朋友推荐了这个,它很有用:

for (var prop in response) {
      if (prop.indexOf('tag_') >= 0) {    // is a tag_ property
        tagNum = prop.substring(4);
        //~ console.log(tagNum);
        hasValue = response[prop] !== '';
        if(response[prop] !== ''){
          //~ alert(tagNum+response[prop]);
          $('#tags-select').append('<option value="'+tagNum+'">'+response[prop]+'</option>');
        }
      }
    }

感谢大家的帮助!