Ajax和jquery重定向

Hi there folks I have a jquery script to submit a form and if successful it sends json output back.

function subscribe(email, city){
    var email = $('input#email').val();
    var city = $('select#citySelect').val();

    $.ajax({
        url: 'http://www.amazingvouchercodes.co.uk/avc_dev/subscribe/subscribeTo',
        type: 'post',
        data: 'email='+email+'&city='+city,
        dataType: 'json',
        success: function(json){
            window.location.href = json['url'];
            $('#notifications').append('<div class="success">'+json['success']+'</div>');
        }
    }); 
}

the problem I have is that it is displaying the notification > json success before the redirect after redirect the notification doesnt show, is there a way to show the notification after the redirect?

Thanks all help is appreciated :)

Joe

You'd have to do something like window.location.href = json['url'] + "?redirMsg=Foo+Bar"; and on your pages check if redirMsg is in the query string, and if so, alert your notification.

Are you saying that you want the success function to cause a redirect, and then update something on the page you were redirected to?

If so, you will need to do it a little differently. The page you get redirected to will not continue executing the javascript that started executing on this first page.

One option is to append a querystring variable to tell the next page to update. Such as:

window.location.href = json['url'] + "?msg=success";

Then on the next page, it would check for that querystring variable, and do the update if it exists.

On the next page, you can include something like:

function getFromQuery(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}

if (getFromQuery("msg")=="success")
{
//do your update here
$('#notifications').append('<div class="success">'+json['success']+'</div>');
}

Like AlienWebguy suggested,

It is because you are loading a new page, so any JavaScript gets reset.

I think the best way would be to have an element set in your layout/header that displays messages on the top of your screen (like how this site notifies you of something in the orange bar) if any are pending. So on your Ajax page, you set a notification (session/cookie) variable. Then the next time a page loads (after your redirect), the layout will know there is a notification pending, it displays it in the layout/header and clears it (so it only shows up once.)