我正在使用$ .ajax()函数在我的应用程序中调用servlet,我正在向aothor jsp页面转发请求并设置请求属性.....我只是想知道它是转发请求和设置的好方法基于ajax的servelt中的请求参数? 这是我的示例代码.....
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>')
}
});
});
这是我的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);
}
如何使用ajax而不刷新页面...... 即使我在ajax成功方法中使用window.location.herf =“list.jsp”它是刷新页面
答案 0 :(得分:1)
当您通过AJAX调用servlet时,无论服务器发送的标头如何,您都可以按定义停留在同一页面上。
如果要更改页面,则必须使用javascript,在$.ajax(..)
调用的成功处理函数中执行此操作。
您可以阅读Location
响应标头并将window.location.href
设置为该值。 See here for other options