java 如何将请求重定向/转发到 $.ajax() 函数调用的 servlet 中的另一个 jsp 页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17696051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect/forward request to another jsp page in servlet called by $.ajax() function
提问by Developer Desk
I am using $.ajax() function to call servlet in my application and i am forwarding request to anothor jsp page and setting request attribute.....I just want to know is it good approach to forward request and setting request parameter in ajax based servelt? Here is my sample code.....
我正在使用 $.ajax() 函数在我的应用程序中调用 servlet,我正在将请求转发到另一个 jsp 页面并设置请求属性.....我只是想知道转发请求和设置请求参数的好方法基于 ajax 的服务器?这是我的示例代码.....
var id= $("#id").val();
$("#add-btn").click(function(e) {
e.preventDefault();
var dataString ='action=insert'+'&id='+id
console.log(dataString);
$.ajax({
type: "POST",
url: "RecordHandler",
data: dataString,
success: function(data){
console.log('Add');
$('body').html(data);
$('body').prepend('<div style="width:100%;text-align:center;"><h3 style="color:green" >Record Added Succesfully</h3></div>')
}
});
});
and here is my servlet code......
这是我的 servlet 代码......
private static String UserRecord = "/list.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String redirect = "";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("insert")) {
String id= request.getParameter("id");
int uid = Integer.parseInt(id);
RecordBean record = new RecordBean();
record.setId(uid);
dao.addRecord(record);
redirect = UserRecord;
request.setAttribute("records", dao.getAllRecords()); //Is it good approach to set request attribute in ajax based servlet?
System.out.println("Record Added Successfully");
RequestDispatcher view = request.getRequestDispatcher(redirect);//Is it good approach to redirect request in ajax based servlet?
view.forward(request, response);
}
How to do it using ajax without refreshing page...... even i use window.location.herf="list.jsp" in ajax success method it is refreshing page
如何在不刷新页面的情况下使用ajax做到这一点......即使我在ajax成功方法中使用window.location.herf =“list.jsp”它也在刷新页面
采纳答案by Bozho
When you call a servlet via AJAX, you stay on the same page by definition, regardless of the headers sent by the server.
当您通过 AJAX 调用 servlet 时,根据定义,您将停留在同一页面上,而不管服务器发送的标头如何。
If you want to change the page, you must do it with javascript, in the success handler function for the $.ajax(..)
call.
如果要更改页面,则必须在$.ajax(..)
调用的成功处理函数中使用 javascript 来完成。
You can read the Location
response header and set the window.location.href
to that value. See here for other options.
您可以读取Location
响应标头并将 设置window.location.href
为该值。请参阅此处了解其他选项。