使用jQuery通过单个ajax请求发送数组和其他数据

时间:2018-12-09 14:10:18

标签: javascript jquery ajax servlets

我有一个Java Servlet,它可以接收页面中的所有请求,并以json形式返回一些数据。我很确定servlet可以,但是我不知道脚本中失败的地方。该脚本具有一个动作参数,该参数是我在servlet中需要了解的字符串,以了解该怎么做,在这种情况下,我还需要传递2个数组(1个int数组和1个String数组)。 Servlet告诉我数组的json格式错误。 js脚本:

$(document).ready(
$.ajax({
        url: "Controller",
        type: "POST",
        data: {action: "load",
               subjects: getSubjects(),
               days: getDays()
              },
        dataType: "json",
        success: function (result) {
            //do stuff

            }
        },
        error: function (xhr, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    }));

Json解析是通过gson完成的:

Integer[] days = gson.fromJson(request.getParameter("days"), Integer[].class);
String[] subjects = gson.fromJson(request.getParameter("subjects"), String[].class);

我尝试了两个数组都为空并且可以工作,但是如果一个或两个都包含的东西则不然。 附言:我在函数中创建数组并返回它们 P.s.2:将元素添加到数组中 P.s.3:我在互联网上搜索了很多内容,但在最新版的jquery中,发生了很多变化,过去的答案不起作用。

编辑:我尝试使用JSON.stringify(getSubjects)和JSON.stringify(getDays),但是没有用

感谢您的关注:)

1 个答案:

答案 0 :(得分:0)

我认为您的getSubjects()getDays()函数在需要JSON字符串时返回一个数组。您可以使用JSON.stringify()生成有效的JSON字符串。

在处理服务器请求时,请确保检查浏览器开发人员工具的网络标签(单击F12在Firefox和Chrome等浏览器上将其打开)。

/*
Wrong Way - Passing array as a parameter
In this way you send the parameters:

  action: load
  subjects[]: 1
  subjects[]: 2
  subjects[]: 3
  days[]: 1
  days[]: 2
  days[]: 3

*/

$.ajax({
    url: "Controller",
    type: "POST",
    data: {
        action: "load",
        subjects: [1, 2, 3],
        days: [1, 2, 3]
    },
    dataType: "json",
    success: function (result) {
        //do stuff
        console.log(result);
    },
    error: function (xhr, thrownError) {
        console.error(xhr.status, thrownError);
    }
});

/*
Correct Way - Passing JSON string as a parameter
In this way you send the parameters:

  action: load
  subjects: [1,2,3]
  days: [1,2,3]

*/
$.ajax({
    url: "Controller",
    type: "POST",
    data: {
        action: "load",
        subjects: JSON.stringify([1, 2, 3]),
        days: JSON.stringify([1, 2, 3])
    },
    dataType: "json",
    success: function (result) {
        //do stuff
        console.log(result);
    },
    error: function (xhr, thrownError) {
        console.error(xhr.status, thrownError);
    }
});

编辑

完整的示例代码:

文件 Test.java

// Import required java libraries
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import com.google.gson.*;
import com.google.gson.Gson;

// Extend HttpServlet class
@WebServlet("/Test")
public class Test extends HttpServlet {

    public void init() throws ServletException {}

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html");

        // Actual logic goes here.
        PrintWriter out = response.getWriter();
        out.println("Test");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Gson gson = new Gson();
        Integer[] days = gson.fromJson(request.getParameter("days"), Integer[].class);
        String[] subjects = gson.fromJson(request.getParameter("subjects"), String[].class);

        // Set response content type
        response.setContentType("text/html");

        // Actual logic goes here.
        PrintWriter out = response.getWriter();
        out.println(
            "days : \"" + Arrays.toString(days) + "\"<br>" +
            "subjects : \"" + Arrays.toString(subjects) + "\"<br>"
        );
    }

    public void destroy() {
        // do nothing.
    }
}

文件 text-ajax.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Test</title>
    </head>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
            jQuery.ajax({
                url: "http://localhost:8080/Test",
                type: "POST",
                data: {
                    action: "load",
                    subjects: JSON.stringify(["a", "b", "c"]),
                    days: JSON.stringify([1, 2, 3])
                },
                /*Just to be sure*/
                contentType : "application/x-www-form-urlencoded; charset=UTF-8",
                dataType: "json",
                success: function (result) {
                    console.log(result);
                },
                error: function (xhr, thrownError) {
                    console.error(xhr.status, thrownError);
                }
            });
        </script>
    </body>
</html>