开发者

What if targeting URL is not returning back

This is the sample code I am using to hit a URL with fixed time interval.

$(document).ready(function() {
    var counter = 1;

    $.doTimeout( 1000, function() {
        $.ajax({
            type: "GET",
            url: "<%=encodeUrl%>",
            timeout: 10000,
            dataType: "text",

            complete: function(resp) {
                if (resp.status == 200) {
                    $("#msg").html(counter++);
                } else {
                    $("#msg").html("Failed");
                    return true;
                }
            }
        });
    });
});

Target URL is a servlet which is forwarding the control to another JSP. As开发者_如何学JAVA per my understanding I must be redirected to new page. But it is showing the same page with the counter value 1. Means, redirect from target servlet is not working. And response is coming back to the same page.


When your AJAX response is a redirect to another page, the redirected page will be fetched as the response of your AJAX request, that's why your are getting only 200 as HTTP status.

You cannot handle redirects based on the HTTP Status codes that you receive with AJAX.

An AJAX response cannot redirect you to a different page unless you program it to do so.

So if you want to redirect based on your AJAX response, you should modify your server side code to send you the redirect URL as a response, rather than redirecting.

Refer one of answers with example solution


AJAX isn't meant to redirect. These headers don't get executed by your browser thus letting you stay on that page! What is the exact code your servlet gives back?


The code is doing exactly what its written to do. You are firing an ajax call, and on response 200 you are setting counter as html for #msg. There is nothing in the code that'll make you redirect to the New Page.

You do not need ajax here if you want to redirect. Else, if your redirect is based on response returned by the servlet, capture it in complete and set window.location.href = 'your/redirect/url/' to load the New Page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜