我试图让JavaScript发送一些HTML作为对来自JavaScript函数的请求的响应。但是,当servlet函数被调用并且似乎正在发送响应时,Javascript函数只得到一个空字符串。
以下是Servlet方法:
String type = request.getParameter("type");
if(type.equals("locos")) {
response.setContentType("text/html");
//this prints out
System.out.println("Responding with vehicle list");
//deal with response
PrintWriter out = response.getWriter();
out.write("<p>test response</p>"); //finish
}下面是JavaScript函数:
this.updateVehicleList = function () {
var type = "locos";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'GetList?type=' + encodeURIComponent(type),true);
xhr.send(null);
//deal with response
var res = xhr.responseText;
//for testing
if (res == "") {
window.alert("I'm getting nothing");
}
view.showVehicleList(res);
};“我什么也得不到”的消息每次都会输出。如何让JavaScript实际接收来自Servlet的响应?
发布于 2016-04-03 11:57:12
您正在发出异步请求,因此响应无法立即可用。您正在尝试在收到响应之前获得responseText。
使用onreadystatechange事件:
...
...
xhr.send(null);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200){
//deal with response
var res = xhr.responseText;
//for testing
if (res == "") {
window.alert("I'm getting nothing");
}
view.showVehicleList(res);
}
};如果您打算提出同步请求,那么将第三个参数设置为false,您的原始代码就可以工作了。
xhr.open('GET', 'GetList?type=' + encodeURIComponent(type),false);
// ^^^^^https://stackoverflow.com/questions/36385018
复制相似问题