2013-06-23 23 views
0

以下JavaScript代碼重定向「成功」有什麼不妥?JavaScript重定向無法正常工作,並且只能在Chrome中運行,如果調試程序已打開

$('#recordUser').click(function() { 
$.ajax({ 
    type: 'POST', 
    url: 'api/RecordUser', 
    data: $("#recordUserForm").serialize(), 
    dataType: 'json', 
    success: function (userEmail) { 
     var newUrl = "/Home/AnotherPage?email=" + userEmail.Email; 
     $(location).attr('href', newUrl); 
     //I have also tried following ways to redirect: 
     //window.location.href = "/Home/AnotherPage?email=" + userEmail.Email; 
     //window.location = "/Home/AnotherPage?email=" + userEmail.Email; 
     //window.location.replace(newUrl); 
    }, 
    error: function (xhr, status, err) { 
     console.log(xhr);    
    } 
}); 
}); 
//#recordUser is a button inside a form with method="post" 

的Html的形式:

 <form id="recordUserForm" accept-charset="UTF-8" method="post"> 
     <div class="..."> 
     <input id="recordUserEmail" class="span6" name="Email" type="text"> 
     </div> 
     <button class="..." id="recordUser">Submit</button> 
     </form> 

我已經在Chrome和Firefox測試這和重定向不上都發生。我已經確保我的服務器代碼工作正常。

在Chrome中,如果我在調試模式下運行javascript,那麼頁面會被重定向到任何重定向命令,但如果關閉調試器,重定向命令將停止工作。

如果我從我的html表單中刪除「method」屬性,那麼URL中的查詢字符串確實會出現,但頁面停留在相同的位置。例如,如果我在localhost:80然後提交表單,那麼URL將變爲localhost:80?email = email而不是預期的newUrl。奇怪的是,如果我在調試中運行它,那麼它按預期工作。爲什麼?

如果有人能指出錯誤,以及上述代碼只能在Chrome調試模式下工作的原因,會很感激/高興嗎?我還想知道如何在「錯誤」回調中打印出有用的錯誤消息?通過有用的我指的是指向錯誤來源的東西(例如異常消息,堆棧跟蹤等),而不是我必須手動插入的東西。

更新1

如果我改變了按鈕的html

 <input class="..." id="recordUser" value="Submit" type="button"/> 

,並在腳本中使用click方法然後正常工作。

我仍然希望能得到一個答案,告訴我如何讓它與button一起工作,以及腳本爲什麼在Chrome調試模式下工作?

更新2

雖然張貼UPDATE1我意識到,我錯過了在HTML中typebutton。也許,我認爲這是因爲它被標記爲button然後指定類型將是多餘的,但它不是。

<button type="button" class="..." id="recordUser">Submit</button> 

以上與原始JavaScript的標記現在按預期工作。所以,我想唯一的問題是爲什麼它在Chrome調試模式下工作呢?

+0

刪除我的答案 - 我沒有時間正確調試 – 2013-06-23 03:22:35

回答

0

如果window.location = "something"失敗,這是因爲兩種可能性之一:

  1. 沒有被執行的代碼,因爲你的Ajax查詢沒有成功(可在一些問題與您後端,使用的console.log成功函數的開始,以檢測它是否被執行)。
  2. 「something」與瀏覽器導航欄中的當前網址完全相同,因此它實際上正在工作。

不要使用這些,因爲他們是完全錯誤的(其他兩種方法是正確的):

  • $(位置).attr( 'href' 屬性,NEWURL);
  • window.location.replace(newUrl);

用於重定向正確的方法是,這些(或者將工作跨瀏覽器):

  • 了window.location = 「東西」;
  • window.location.href =「something」;
+0

嗨,感謝您的信息。當你回答時,我已經在同一時間更新了這個問題。看看問題的結尾。 – sttaq