JSON数组作为ajax请求数据

时间:2014-11-08 12:53:16

标签: ajax json servlets

如何将数组作为ajax请求数据传递以及如何在servlet中访问它?

var a=[0,1,2,3];
 $.ajax({
                type: "GET",
                 url: "/accessarray",                    
                    data: { param:a},
                 success: function(data) {$('#results').html("success");
                }
            });

1 个答案:

答案 0 :(得分:0)

像这样传递你的数组:

var myArr = [1, 2, 3, 4];

$.ajax({
  type: "POST",
  url: "YOUR SERVLET NAME",
  data: "{myArr: " + myArr + "}", 
  // what ever the data you need to pass to server to generate yout "String"

  success: function(result) {

    console.log(result);
  },
  error: function(error) {

    console.log("error" + error);
  }
});

在Servlet中,尝试将您的值作为String数组:

String[] myArr = request.getParameterValues('myArr');

如果需要以整数数组的形式访问它,只需循环myArr并通过解析为Integer.parseInt(myArr [index])将值分配到新的int数组中;

希望这会对你有帮助!