想要在同一页面上导航页面

时间:2013-04-27 12:57:08

标签: java servlets

我的ajax有些看起来像这样:     function getXMLHttpRequest(){       var xmlHttpReq = false;       if(window.XMLHttpRequest){         xmlHttpReq = new XMLHttpRequest();       } else if(window.ActiveXObject){         试试{

      xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (exp1) {
      try {

        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (exp2) {
        xmlHttpReq = false;
      }
    }
  }
  return xmlHttpReq;
}

function makeRequest() {
  var xmlHttpRequest = getXMLHttpRequest();
  xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
  xmlHttpRequest.open("POST", "http://abc.com:8080/someservletServlet/", true);
  xmlHttpRequest.setRequestHeader("Content-Type",
      "application/x-www-form-urlencoded");
  xmlHttpRequest.send(null);
}


function getReadyStateHandler(xmlHttpRequest) {

    return function() {
    if (xmlHttpRequest.readyState == 4) {
      if (xmlHttpRequest.status == 200) {

          document.getElementById("xml").value = xmlHttpRequest.responseText;
      } else {
        alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
      }
    }
  };
}   but somehow the servlet is not bringing the response it should bring. can you help. what could be the possible error.

2 个答案:

答案 0 :(得分:0)

Ajax是要走的路。因为如果你提交请求,页面会刷新它的相同页面还是不同。

如果你仍然希望在不使用ajax的情况下使用它来实现它并且刷新页面就可以了,那么看看你的servlet中是否有这种代码导致它转发到其他页面

  String nextJSP = "nextPage.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);

答案 1 :(得分:0)

如果您需要从其他URL加载一些数据,您需要发送一个AJAX请求(解释从何处获取数据)并处理AJAX响应(解释如何处理所获取的数据)。要提供与浏览器兼容的解决方案,您最好使用一些着名的JS库。例如,您可以使用jQuery,在这种情况下您的脚本可能如下所示:

$.ajax({
    url: "servletURL",//servlet URL to post data to
    type: "POST",//request type, can be GET
    cache: false,//do not cache returned data
    data: {id : idOfData},//data to be sent to the server
    dataType: "xml"//type of data returned
}).done(function(data) {
    //do something with XML data returned from server
});

使用这种方法,您需要在一些JS事件(即click)上调用上面的JS代码(可能包含在JS函数中),并处理响应数据,例如,通过将其内容附加到文本区域