Ajax响应返回null

时间:2015-03-03 18:11:32

标签: java javascript html ajax xml

我是Ajax的新手并且刚刚开始学习,我已经设法将数据传递给我的servlet但是一旦我回写它然后尝试从我的网页读取它返回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);
            }
        }

我希望有人能指出我正确的方向,谢谢

2 个答案:

答案 0 :(得分:1)

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标记。如果您不想要root,则可以删除documentElement部分,如

//Java - No change
response.getWriter().println("<responseFromServer>The date is" + request.getParameter("date")+"</responseFromServer>");

//Ajax
var date = xmlhttp.responseXML.getElementsByTagName("responseFromServer")[0];

答案 1 :(得分:0)

没关系已经发现了问题,感谢Syam S指出我正确的方向,对于任何遇到与我相同的问题,这是解决方案。

var date = xmlhttp.responseXML.getElementsByTagName("responseFromServer")[0].childNodes[0].nodeValue;