我是Ajax新手,刚刚开始学习,我已经成功地将数据传递给了我的servlet,但是一旦我写回它,然后尝试从我的web页面读取它,它就会返回undefined这里是我的代码:
爪哇语:
@WebServlet("/PeriodHandler")
public class PeriodHandler extends HttpServlet {
private static Connection conn = UserHandler.conn;
private String periodList;
public String date;
public PeriodHandler(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/xml");
System.out.println(request.getParameter("date"));
response.getWriter().println("<responseFromServer>The date is" + request.getParameter("date")+"</responseFromServer>");
}
}
Javascript代码:
function sendData() {
xmlhttp.open("POST", "PeriodHandler?date=" +document.getElementById('dates').value, true);
xmlhttp.onreadystatechange=recievedMessageFromServer;
xmlhttp.send();
}
function recievedMessageFromServer(){
if(xmlhttp.readyState===4 && xmlhttp.status===200){
var date = xmlhttp.responseXML.documentElement.getElementsByTagName("responseFromServer")[0];
alert(date);
}
}
我希望有人能指引我正确的方向,谢谢
最佳答案
responseFromServer
是根元素。尝试将其包装在另一个内部并访问responseFromServer
//Java
response.getWriter().println("<root><responseFromServer>The date is" + request.getParameter("date")+"</responseFromServer></root>");
//Ajax - No change
var date = xmlhttp.responseXML.documentElement.getElementsByTagName("responseFromServer")[0];
这里的想法是当您调用
xmlhttp.responseXML.documentElement
时,它从根开始。因此,它检查responseFromServer
标记是否有responseFromServer
的子元素。如果你不想要根,你可以移除documentElement
部分//Java - No change
response.getWriter().println("<responseFromServer>The date is" + request.getParameter("date")+"</responseFromServer>");
//Ajax
var date = xmlhttp.responseXML.getElementsByTagName("responseFromServer")[0];