简体   繁体   English

将JavaScript数组发送到Servlet

[英]Sending an javascript array to a servlet

Hello I have been looking at other threads like mine and I can't seem to get my code working! 您好,我一直在寻找其他线程,例如我的线程,但似乎无法使我的代码正常工作!

I need to send the JS array containing ints to a servlet this is current code: 我需要将包含int的JS array发送到servlet,这是当前代码:

Javascript code : 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 Code : Servlet代码

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

It keeps returning null! 它不断返回null! Can someone tell me if I am doing something wrong ? 有人可以告诉我我做错了什么吗?

in "$ajax" you need to pass the required parameter, eg 在“ $ ajax”中,您需要传递所需的参数,例如

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

You must use JSON.stringify to send your JavaScript object as JSON string. 您必须使用JSON.stringify将您的JavaScript对象作为JSON字符串发送。

Change your code 更改您的代码

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

On Servlet side you need you use 在Servlet方面,您需要使用

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

then Convert this jsonStr to JSON object. 然后将此jsonStr转换为JSON对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM