繁体   English   中英

如何将javascript数组发送到Servlet

[英]How to send a javascript array to the Servlet

我有一个应用程序,我在控制台中以javascript数组的形式获取一些值。现在我想将值发送到servlet.My javascript数组看起来像这样..

0.Java
1.Perl
2.C#

我在控制台得到的这个值。我必须将这些值发送到Servlet.But我不能那样做。我能够向Servlet发送多个值,但不知道如何发送javascript数组。我的方式向Servlet发送多个值

 $.ajax({
        url: "AccountServlet",
        type: "post",

        dataType: "json",
        data: { subject1:java,subject2:perl..etc},
        error:function(){
            //alert("error occured!!!");
        },
        success:function(data){
            alert(data.fullName + "\n" + data.mobileNo);
        }
     });

在Servlet中,我抓住它们

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String sub1=request.getParameter("subject1");
            String sub2=request.getParameter("subject2);
    ;

像这样,但任何人都可以帮助我如何在这里存储javascript数组。 }

有几种方法可以解决这个问题,但最简单的方法是将数组作为javascript代码中的一个参数传递,然后在Java代码中将其作为字符串检索。 使用像GsonSimple JSON这样的JSON库将数组从字符串解析为本机Java数组。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Gson gson = new Gson();
String[] arr = gson.fromJson(request.getParamenter("subjects"), String[].class); 
 // ... do more here
}

暂无
暂无

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

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