How to call a javascript function from a servlet?
I submit a (jsp) form to a Servlet A. Then I handle some logic which would make the submission either a success or a failure. I use jquery's ajaxForm() function to re-direct the user to a different jsp after the Servlet logic is executed. But before this redirection happens I need to show a javascript notification showing whether the s开发者_开发技巧ubmission was successful or not. Can someone tell me how can I do this?
Use the success
callback handler. This will be invoked whenever the servlet has returned a response. You can access the returned response as 1st argument in the callback handler. Easiest way would be to let the servlet return a JSON response so that you can access it as a JavaScript object:
$('#formId').ajaxForm({
dataType: 'json',
success: function(response, status, xhr) {
if (response.error) {
alert('Something failed: ' + response.error);
} else {
alert('Submit was successful.');
window.location = 'newpage.jsp';
}
}
});
In the servlet you need to return the response something like as:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
if (submit was not successful) {
response.getWriter().write("{ error: '" + message + "' }");
} else {
response.getWriter().write("{ error: false }");
}
精彩评论