首页 文章

使用jquery使用单个ajax请求发送数组和其他数据

提问于
浏览
1

我有一个java servlet,它接收来自我的页面的所有请求,并以json的形式返回一些数据 . 我很确定servlet是可以的,但我不明白我在脚本中失败了 . 该脚本有一个action参数,我需要在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);

我尝试将两个数组都清空并且它可以工作,但如果其中一个或两个包含它没有的东西 . Ps:我在函数中创建数组并返回它们Ps2:使用push Ps3将元素添加到数组中:我在互联网上搜索了很多但是在最新版本的jquery中,很多东西都改变了,过去的答案也没有不行 .

编辑:我试过JSON.stringify(getSubjects)和JSON.stringify(getDays),但它没有工作

谢谢你的关注:)

1 回答

  • 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>
    

相关问题