【问题标题】:How to send a javascript array to the Servlet如何将 javascript 数组发送到 Servlet
【发布时间】:2013-12-21 20:27:46
【问题描述】:

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

0.Java
1.Perl
2.C#

我在控制台中获得的这些值。我必须将这些值发送到 Servlet。但我不能这样做。我能够向 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 arrays servlets


    【解决方案1】:

    有几种方法可以处理这个问题,但最简单的方法是将数组作为一个参数传递到您的 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
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-04
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 2013-12-31
      • 2013-01-26
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多