How do you send an array as part of an (jquery) ajax request

后端 未结 2 499
情歌与酒
情歌与酒 2021-01-24 20:43

I tried to send an array as part of an ajax request like this:

var query = [];
// in between I add some values to \'query\'
$.ajax({
    url: \"MyServlet\", 
            


        
2条回答
  •  野性不改
    2021-01-24 20:55

    Just try to send the data as name/value pair (which is expected). Like

    var query = ["data1","data2"];
    // in between I add some values to 'query'
    $.ajax({
        url: "MyServlet", 
        data: {'query' : query},
        success: function(noOfResults) { 
        alert(noOfResults); 
        }
      });
    }
    

    You should get the data at server side like this

    query => Array ( [0] => data1 [1] => data2 )
    

    As per the jQuery documentation for data setting of jQuery.Ajax() method

    If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting

提交回复
热议问题