简体   繁体   中英

Problem using sendRedirect in a servlet using Jquery + AJAX

I'll try to explain my questions/problem easily.

In my jsp I have some links, one for each message of the forums. When I click any of the ".delete" links, the following script is triggered:

$('.delete').click(function(event) {
    event.preventDefault();

    // some data recovering from the jsp's tags
    var idMsg = $(this).closest('.li').attr('id');
    var action = $(this).attr('name');
    var origin = $('div#origin').attr('name');
    ...

    // some checking
    //alert('id: '+idMsg);
    ...

    // I send the info to delete the message in the servlet
    $.post("../app/ForumCampus", {action:action, idMsg:idMsg, origin:origin}, function(data) {
    });

    //$('.output').append('Message deleted successfully.');
});

At first, I didn't want to refresh the page and I only showed the above success message.

But now, due to pagination, I need to refresh the servlet, and I have the following code in the post method:

response.sendRedirect(contextPath+"/app/" + origin);

But when AJAX goes to the servlet, does all the stuff (deletes the message correctly) but does not redirect to the servlet. The page didn't refresh. If I refresh the page manually It's all OK, the deleted message doesn't appear.

My questions are:

1) The servlet doesn't redirect because the script isn't finished yet? Why?

2) I can refresh the servlet just typing the following code in the.click event:

location.reload();

But, there is way that you consider better? Without using Javascript or something?

Thanks for advance, learning with you is so cool:)

Obviously, your Ajax call does not perform a redirect in the browser, how should that work? Remember, it's an asynchronous call 'behind the scenes'.

If you want to control the redirects using Ajax, you have to examine the result of the Ajax call (the HTTP headers) and then manually redirect using JavaScript (eg using document.location ).

BTW: I think this is not a good idea. In case of complex Ajax application, the Javascript functions play the role of what MVC pattern calls the controller. So, your Ajax function should know when to redirect.

I think Ajax is used for Asynchronous java script and XML and it run in background so rather than redirect you can simply get all value of html input tag using request.getparameter() in servlet and redirect that servlet using

Javascript or jquery:

 document.<formname>.action="<%=response.encodeURL("<sevlet name>")%>";
 document.AdminForm.submit();   

Is this suitable for you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM