0

我的 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.
4

2 回答 2

0

Ajax 是要走的路。因为如果您提交请求,页面将刷新,无论是相同的页面还是不同的页面。

如果您仍然想在不使用 ajax 的情况下使用它并且刷新页面对您来说很好,那么请查看您的 servlet 中是否有这种代码导致将其转发到其他页面

  String nextJSP = "nextPage.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
于 2013-04-27T13:02:20.553 回答
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 事件 ie 上调用上述 JS 代码(可能包装在 JS 函数中click)并处理响应数据,例如,通过将其内容附加到您的文本区域。

于 2013-04-28T07:36:46.047 回答