ajax 访问接口success后无法跳转问题的解决

今天写一个ajax登陆的js方法  登陆成功后发现无法跳转,刚开始用的是

window.location.href="index.html";  控制台报错说这一行不是一个方法

然后换成location.href="index.html";  还是提示错误,一直百思不得其接,这两个方法不用ajax提交是可以用的,代码如下

<script>
	function login(){
		var phone = document.getElementById("phone").value;		
		var password = document.getElementById("password").value;
//		console.log("phone="+phone); 
 		$.ajax({       
            type: "POST",
            url: "http://172.18.1.74:8081/parentServer/login.do",                 
            async: true,                
            data: {
            	phone: phone,
            	password : password
            },
            dataType: "json",
            success: function(result) {
 //             console.log(result); 
				if(result==true){
					console.log("登陆成功");
					location.href("index.html"); 

				} else{
					console.log("账号或者密码错误"); 
				}
            },
            error: function() {
           	 	console.log("访问失败");
            }
        }); 
	}
</script>

后来才发现这两种方法是js原生的跳转方法,而$.ajax({...});是用的jQuery的方法,所以无法识别,如果想跳转必须用jQuery的跳转方法

$(location).attr('href', 'index.html');

代码如下

<script>
	function login(){
		var phone = document.getElementById("phone").value;		
		var password = document.getElementById("password").value;
//		console.log("phone="+phone); 
 		$.ajax({       
            type: "POST",
            url: "http://172.18.1.74:8081/parentServer/login.do",                 
            async: true,                
            data: {
            	phone: phone,
            	password : password
            },
            dataType: "json",
            success: function(result) {
 //             console.log(result); 
				if(result==true){
					console.log("登陆成功");
//					location.href("reset-password.html"); 
//					$("#form1").attr("action",contextPath+'/success');
					$(location).attr('href', 'index.html');
				} else{
					console.log("账号或者密码错误"); 
				}
            },
            error: function() {
           	 	console.log("访问失败");
            }
        }); 
	}
</script>
这样就可以了.

猜你喜欢

转载自blog.csdn.net/u012954380/article/details/80783942