2012-08-02 26 views
0

在執行AJAX成功後,我似乎無法重定向到新頁面(這是在jQuery Mobile的腳本中)。在下面的代碼中,如果我執行除重定向以外的其他功能,則sessionStorage會按預期設置。執行重定向時,sessionStorage代碼不會執行。建議?AJAX重定向成功覆蓋其他邏輯

$("#register").click(function() { 

    var formData = $("#registerUser").serialize(); 

    $.ajax({ 
     type: "POST", 
     url: "file.php", 
     //dataType:'json', 
     cache: false, 
     data: formData, 
     //success: onSuccess, 
     success: function (data) { 
      if (data.status == 'success') { 

       //execute some code here 
       var someValue = (data.id); 
       sessionStorage.setItem('someValue', someValue); 

      } else if (data.status == 'error') $("#notification").text(data.message); 
     }, 

     complete: function() { 
      window.location.replace('newPage.html'); 
     } 
    }); 

    return false; 
}); 
+0

請注意,這是唯一的瀏覽器有問題。在Firefox中,一切都按預期工作。 – byoung 2012-08-02 19:46:08

回答

-1

想通了這出自己 - 你必須使用JQM重定向:$.mobile.changePage('newPage.html');

success: function (data) { 
    if (data.status == 'success') { 

     //execute some code here 
     var someValue = (data.id); 
     sessionStorage.setItem('someValue', someValue); 

     // redirect after success 
     $.mobile.changePage('newPage.html'); 

    } else if (data.status == 'error') { 
     $("#notification").text(data.message); 
    } 
} 
+0

原始問題上沒有提及JQM。 – WhyNotHugo 2012-08-03 15:40:32

+0

感謝雨果 - 我編輯了這個問題來表明它是用於JQM – byoung 2012-08-04 15:25:15

1

您的成功和完成是相沖突的。兩者都會在完成時執行。一個會重定向。將重定向代碼移到成功,以便在重做其他事情之後重定向代碼。

success: function (data) { 
    if (data.status == 'success') { 

     //execute some code here 
     var someValue = (data.id); 
     sessionStorage.setItem('someValue', someValue); 

     // redirect after success 
     window.location.replace('newPage.html'); 

    } else if (data.status == 'error') { 
     $("#notification").text(data.message); 
    } 
} 
+0

我其實第一次嘗試過,結果相同。頁面重定向而不保存sessionStorage值(僅限Chrome) – byoung 2012-08-02 19:49:20

+0

如果你取出重定向,一切正常(在Chrome中),對吧? – sachleen 2012-08-02 19:50:52

+0

是的 - sessionStorage設置正常,但沒有重定向。 – byoung 2012-08-02 19:55:46