我正在尝试从servlet将JSON数据发送到我的JSP页面。 一旦我运行JSP,整个JSP就会被JSON内容覆盖。为什么会这样?这是我的JSP页面的一部分。
<%@ page import="java.util.ArrayList" %>
<head>
<script>
function populateTypeOfWork(workType) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var work = JSON.parse(this.responseText);
workType.options.length = 0;
for (i = 0; i < work.length; i++) {
createOption(workType, workDesc[i], workDesc[i]);
}
}
xhttp.open("GET", "ServletRequest", true);
xhttp.send();
}
}
function createOption(dropdown, text, value) {
var x = document.createElement('option');
x.value = value;
x.text = text;
dropdown.options.add(x);
}
</script>
</head>
<body>
<label>Work Category **</label>
<select id="workCategory"
onchange="populateTypeOfWork(document.getElementById('workTypeDesc1'))"
size=1
style="width:95%;" required>
<option value="" selected>Select A Work Category</option>
<% ArrayList workCategory = (ArrayList)
request.getAttribute("workCategory");
for (int i = 0; i < workCategory.size(); i++) {
%>
<option value="<%=workCategory.get(i)%>"><%=workCategory.get(i)%>
</option>
<% } %>
</select> <br>
<label>Type Of Work **</label>
<select id="workTypeDesc1" size=1 style="width:95%;" required>
<option value="" selected>Type of Work</option>
</select>
</body>
</html>
的Servlet
String json = new Gson().toJson(arraylistvar);
res.setContentType("application/json");
PrintWriter pw = res.getWriter();
pw.flush();
pw.close();
req.setAttribute("viewURL","/page1.jsp");
为什么stackoverflow要求我添加更多细节?因为它主要是代码.. ??我为什么要不必要地填写这篇文章?
答案 0 :(得分:0)
我可以通过当前代码看到两个问题:(1)您正在引用一个不存在的变量workDesc;看来你应该引用名为work的变量,并且(b)发送AJAX请求的代码在onreadystatechange()事件处理程序中,当它应该在设置事件处理程序之后实际执行时。以下是修订后的代码段:
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var work = JSON.parse(this.responseText);
workType.options.length = 0;
for (i = 0; i < work.length; i++) {
createOption(workType, work[i], work[i]);
}
}
}
xhttp.open("GET", "ServletRequest", true);
xhttp.send();
答案 1 :(得分:-1)
这可能是由于您的网页发出请求的原因。你应该使用AJAX调用;确保您没有在JavaScript中提交普通表单或更改页面的URL。