以下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中type
爲button
。也許,我認爲這是因爲它被標記爲button
然後指定類型將是多餘的,但它不是。
<button type="button" class="..." id="recordUser">Submit</button>
以上與原始JavaScript的標記現在按預期工作。所以,我想唯一的問題是爲什麼它在Chrome調試模式下工作呢?
刪除我的答案 - 我沒有時間正確調試 – 2013-06-23 03:22:35