这里在下面的代码我想通过ajax调用一个servlet然后我将数据从servlet重定向到jsp.ajax调用servlet工作正常但问题是重定向到jsp页面没有显示在浏览器中当我使用没有ajax的javascript代码时,会显示相同的jsp页面。
jspfile中的javascript ajax代码:
function generate(){
...
...
var url="RedirectServlet";
var ajax=new AJAXInteraction(url,"RedirectServlet");
var param ="FD="+FD+"&TD="+TD+"&actionid="+status+"&usercode="+usercode+"&action=reports"+"";
ajax.send(param);
....
}
function AJAXInteraction(url, actionType) {
this.url = url;
var req = init();
var actionRequested = actionType;
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest () {
if (req.readyState == 4) {
if (req.status == 200) {
if(actionRequested=="TestDelegation") {
PostProcess1(req.responseXML);
}
}
}
}
this.send = function(param) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(param);
}
}//end of AJAX Interaction object.
Servlet代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("calling doPost() ");
response.setContentType("text/html;charset=WINDOWS-1256");
String action=request.getParameter("action");
System.out.println(action);
if(action.equals("reports")){
System.out.println("inside reports");
//Getting values from Reports_arb.jsp
String Fromdate=request.getParameter("FD");
String Todate=request.getParameter("TD");
String status=request.getParameter("actionid");
String usercode=request.getParameter("usercode");
//placing given values in a session
request.setAttribute("FD", Fromdate);
request.setAttribute("TD", Todate);
request.setAttribute("actionid", status);
request.setAttribute("usercode", usercode);
//Redirecting to showReport_arb.jsp
//response.sendRedirect("showReport_arb.jsp");
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/sample.jsp").forward(request, response);
答案 0 :(得分:8)
您需要了解以下事实:当您从ajax发送http请求时,这意味着您在单独的线程中而不是在主线程(您发送请求的页面本身)中发送请求。因此,servlet上的重定向不会反映在客户端。为了实现这一点,请将要重定向的URL作为对请求的响应发送回来,并且在ajax的成功方法上只需使用java脚本window.location(URL);
在servlet
JSONObject jobj = new JSONObject()
String urlToRedirect = "test.jsp";
jobj.put("url",urlStr);
response.getWriter().write(jobj.toString());
在客户端
$.ajax({
url: 'servletName',
data: {
userID: selectedID
},
type: 'post',
success: function(data){
window.location = data.url;
}
});
答案 1 :(得分:0)
使用request
而不是创建response
和jquery Ajax
对象。它使用起来非常简单。
/* Send the data using post and put the results in a div */
$.ajax({
url: "/YourServlet",
type: "post",
data: values,
success: function(){
alert("success");
$("#result").html('submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});