我正在使用 $.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>')
}
});
});
这是我的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" 它正在刷新页面