javascript - 使用 jquery 通过单个 ajax 请求发送数组和其他数据
问题描述
我有一个 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);
我尝试将两个数组都为空并且它可以工作,但是如果一个或两个都包含它不包含的东西。Ps:我在函数中创建数组并返回它们 Ps2:通过推送将元素添加到数组中 Ps3:我在互联网上搜索了很多,但在最新版本的 jquery 中,很多东西发生了变化,过去的答案没有工作。
编辑:我尝试使用 JSON.stringify(getSubjects) 和 JSON.stringify(getDays) 但它没有用
感谢您的关注:)
解决方案
我认为您的getSubjects()
andgetDays()
函数在您需要 JSON 字符串时返回一个数组。您可以使用JSON.stringify()
.
在处理服务器请求时,请务必检查浏览器开发工具的网络选项卡(单击 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);
}
});
编辑
完整的工作示例代码:
文件测试.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>