我想检查数据库中是否已存在name
。所以我会做一个帖子。我们假设这个名字已经存在。
如何使用错误:ajax的函数抛出错误以便在html中显示错误?
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
//Check if name exists and return true or false
if(exists)
throw error to ajax
}
//else save data
}
//Ajax Post
$('#btnSubmit').click( function() {
$.ajax({
type: 'post',
url: 'GeneralSetup',
data: data,
success: function () {
window.location.href = "/clients.jsp";
},
error: function () {
}
});
return false;
});
答案 0 :(得分:1)
在服务器上发送4XX(客户端错误)或5XX(服务器错误)的http响应代码就足够了。
在您的情况下,您可以使用response.sendError(400)
- 意味着错误的请求。
List of HTTP status codes.
答案 1 :(得分:1)
我们可以做两种方式
2)使用响应参数
将信息传递给前端@覆盖 protected void doPost(HttpServletRequest request,HttpServletResponse response)抛出ServletException,IOException { String name = request.getParameter(“name”);
//Check if name exists and return true or false
if(exists)
response.setStatus(4XX)
or
PrintWriter writer = response.getWriter();
writer.println("userAlready is Exist");
}
//else save data
}
//Ajax Post
$('#btnSubmit').click( function() {
$.ajax({
type: 'post',
url: 'GeneralSetup',
data: data,
success: function (data) {
if(data =='userAlready is Exist' && data!=null){
$('#some Div TAg Id').html(data);
}else{
//write redirect code
window.location.href = "/clients.jsp";
}
},
error: function (xhr, ajaxOptions, thrownError) {
var errorMsg = 'Ajax request failed: ' + xhr.responseText;
$('##some Div TAg Id').html(errorMsg);
}
});
return false;
});