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

后端 未结 2 494
情歌与酒
情歌与酒 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

    0 讨论(0)
  • 2021-01-24 21:03

    You have to send an object which you first stringify with JSON.stringify.

    like this:

    var query = [];
    // in between I add some values to 'query'
    $.ajax({
        url: "MyServlet",
        data: JSON.stringify({ nameParameter: query })
        dataType: "json",
        success: function(noOfResults) {
            alert(noOfResults);
        }
      });
    }
    
    0 讨论(0)
提交回复
热议问题