最近在寫程序時,都是使用ajax來傳遞數據的。今天在寫程序時,出現了既要傳遞數據,又要跳轉頁面的情況。雖然一般遇到這種情況後,我們可不再使用ajax來操作。不過,今天,心血來潮想試着用ajax來實現。
因爲ajax是無跳轉功能的,所以,在Controller層使用return new ModelAndView()肯定是行不通的,所以我們唯一可以做手腳的地方應該是當ajax返回成功數據時,來做處理。於是,我就嘗試了在success的返回方法中,使用了window.location.href,結果成功了。具體代碼如下所示
<script type="text/javascript">
function onClick1() {
var pwd1 = document.getElementById("password1").value;
var pwd2 = document.getElementById("password2").value;
var userName=document.getElementById("username").value;
if (pwd1 == pwd2) {
var user = {
username : userName,
password : pwd1
};
$.ajax({
url : "../user/adduserReturn",
type : "post",
data : user,
async : false,
success : function(data) {
window.location.href="test";
}
});
} else {
alert("您輸入的兩次密碼不一致");
}
}
</script>