将javascript数组发送到servlet

时间:2014-12-01 10:26:33

标签: java javascript jquery arrays servlets

你好我一直在寻找像我这样的其他线程,我似乎无法让我的代码正常工作!

我需要将包含整数的JS array发送到servlet,这是当前代码:

Javascript代码

function sendReminderEmails(){
$("#sendReminderEmails").click(function(){

var people = null;
var peopleBatch1 = null;

$.ajax({
    type: "POST",
    url:"getAllUnregisteredPeople",
    async: false,  
    success: function(data){      
    people =JSON.parse(data);
  }
});

 peopleBatch1 = people.splice(0,200);

 $.post("sendReminderEmails", {people:peopleBatch1,  mode : "insert"} , function(data){

   });
 });    
}

Servlet代码

protected void doPost(HttpServletRequest request, HttpServletResponse response){    
  String peopleIDs[] = request.getParameterValues("people");    
}

它不断返回null!有人可以告诉我,如果我做错了吗?

2 个答案:

答案 0 :(得分:0)

在“$ ajax”中你需要传递所需的参数,例如

   var myArray={'john', 'paul'};
   $.ajax ({
            type: "POST",
            url:"getAllUnregisteredPeople",
            data: {people: myArray}
            async: false,  
            success: function(data) {      
                people = JSON.parse(data);
            }
        });

答案 1 :(得分:0)

您必须使用JSON.stringify将JavaScript对象作为JSON字符串发送。

更改您的代码

var obj = { people: peopleBatch1, mode: "insert" };
$.post("sendReminderEmails",JSON.stringify(obj) , function(data) {});

在Servlet端,您需要使用

String jsonStr = request.getParameter("people");

然后将此jsonStr转换为JSON对象。