无法使用javascript重定向 [英] Cannot redirect using javascript

查看:40
本文介绍了无法使用javascript重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面可以验证信用卡凭证.一切都很好,直到我需要将用户重定向到另一个页面为止.

I have a page that verifies credit card credentials. It's all well and good until I need to redirect the user to a another page.

function vNumarCard(numar)
{
    console.log(numar);
  var cardno = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;
  if(!numar.match(/^(?:4[0-9]{12}(?:[0-9]{3})?)/))
        {
      return false;
        }
      else
        {
        
        return true;
        }
}

function vDataExp(data){
    console.log(data);
    if(!data.match(/(0[1-9]|1[0-2])[/][0-9]{2}/)){
        
        return false;
    }
    else{
        
        var d = new Date();
        var anCurent = d.getFullYear();
        var lunaCurenta = d.getMonth() + 1;
        var parti = data.split('/');
        var an = parseInt(parti[1], 10) + 2000;
        var luna = parseInt(parti[0], 10);
         if (an < anCurent || (an == anCurent && luna < lunaCurenta)) {
             alert("Card expirat!")
            return false;
         }
         
         return true;

}
}

function vCVC(cvc){
    console.log(cvc);
    if(!cvc.match(/[0-9][0-9][0-9]/)){
        
        return false;
    }
    else{
        return true;
    }
}

function verCard(numar,data,cvc){
    if(vNumarCard(numar)==true&&vDataExp(data)==true&&vCVC(cvc)==true){
        alert('inside if');
        location.href = '/success.html';
    }
    else if(vNumarCard(numar)==false) alert("Numarul cardului este invalid!");
        else if(vDataExp(data)==false) alert("Data expirarii este invalida");
            else alert("CVC incorect!");
}

function verDate(){
    var numar = document.getElementsByName("numarCard")[0].value;
    var data = document.getElementsByName("dataExp")[0].value;
    var cvc = document.getElementsByName("codCVC")[0].value;

    verCard(numar,data,cvc);
}

<!DOCTYPE html>
<html lang="ro">
<head>
	<title>Cumpara</title>
<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="node_modules/bootstrap/scss/bootstrap.css">
	
</head>
<body>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark justify-content-center">
				<ul class="navbar-nav">
					<li class="nav-item">
						<a class="nav-link" href="index.html">Acasă</a>
					</li>
					<li class="nav-item">
						<a class="nav-link" href="modele.html">Modele</a>
					</li>
					
					<li class="nav-item">
						<a class="nav-link" href="galerie.html">Galerie</a>
					</li>
					<li class = "nav-item">
						<a href="cos.html" class = "nav-link">
          					<span class="glyphicon">&#128722;</span>
       					 </a>
					</li>
				</ul>
				
	</nav>

<div class="container">
	<div class="row">
		<div class="col-sm-4">
		</div>
		<div class="col-sm-4">
			<h2 style="text-align: center;">Cumpara produsele selectate</h2>
			<form method="POST">
				
				<div class="form-group">
					<label for="email">
						Email:
					</label>
					<input type="email" name="email" class="form-control" placeholder="Email">
					
				</div>
				<div class="form-group">
					<label for="numeCumparator">
						Nume:
					</label>
					<input type="text" name="numeCumparator" class="form-control" placeholder="Nume">
					
				</div>
				<div class="form-group">
					<label for="numarCard">
						Numar Card:
					</label>
					<input type="text" name="numarCard" class="form-control" placeholder="1234 1234 1234 1234">
					
				</div>
				<div class="form-group">
					<label for="dataExp">
						Data de expirare:
					</label>
					<input type="text" name="dataExp" class="form-control" placeholder="ll/aa">
					
				</div>
				<div class="form-group">
					<label for="codCVC">
						CVC:
					</label>
					<input type="text" name="codCVC" class="form-control" placeholder="CVC">
					
				</div>
				<button name="cumpara" type="submit" class="btn btn-success btn-lg btn-block" onclick="verDate();">Cumpara</button>
			</form>
		</div>
		<div class="col-sm-4"></div>
	</div>
</div>

<script src="node_modules/jquery/dist/jquery.min.js"></script>
	<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
	<script src="scripturi/cumpara.js"></script>
</body>
</html>

每个函数都可以正常工作,我检查了每个函数,并使用警报来查看if是否有效.我在其他页面上使用了相同的方法,效果很好,但是location.href不起作用.我也尝试了document.location.href和window.location,但是得到了相同的结果.实际发生的是,同一页面被重新加载而不是被重定向.

Every function works corectly, I checked each of them and I used the alert to see if the if works and it does. I used the same method on other pages and it works well but location.href doesn't work. I have also tried with document.location.href and window.location but I get the same result. What actually happens is that the same page gets reloaded instead of getting redirected.

推荐答案

发生的事情是,单击提交"按钮时,您的表单被提交.由于您的表单没有 action 属性,因此该表单将提交到当前URL,这就是重新加载同一页面的原因.事件处理程序是在默认操作(表单提交)之前执行的,因此即使您尝试在事件处理程序中重定向,也会被表单提交覆盖,这就是为什么取消重定向的原因.

What happens is that your form gets submitted when clicking the submit button. Since your form doesn't have an action attribute, the form gets submitted to the current URL which is why the same page reloads. Event handlers are executed before the default action (the form submission) so even though you try to redirect in your event handler, this gets overridden by the form submission which is why the redirect gets cancelled.

解决方案是阻止表单提交.首先,您应该在表单上使用 onSubmit 侦听器,而不是按钮上的 onClick 侦听器.您不必那样做,但是它被认为是一种很好的做法,它对可访问性有所帮助.
您需要将 event 参数传递给函数,如下所示:

The solution is to prevent the form submission. First of all, you should use the onSubmit listener on the form instead of the onClick listener on the button. You don't have to do it like that but it's considered good practice and it helps with accessibility.
You need to pass in the event argument to your function, like this:

<form onSubmit="verDate(event);">

在您的 verDate()函数中,您现在可以使用该事件对象来阻止表单提交,如下所示:

In your verDate() function, you now use that event object to prevent the form submission, like this:

function verDate(event){
    event.preventDefault();
    var numar = document.getElementsByName("numarCard")[0].value;
    var data = document.getElementsByName("dataExp")[0].value;
    var cvc = document.getElementsByName("codCVC")[0].value;

    verCard(numar,data,cvc);
}

这应该可以解决您的问题,但是我也想建议,一种更简洁的方法是将成功页面设置为表单的action属性(而不是显式重定向)(即<表单action ="/success.html"> )而不是在表单有效时进行重定向,而是在

event.preventDefault() only 时运行 event.preventDefault() 表单无效.这是使用表单的正确方法,尽可能多地利用默认行为.

That should solve your issue, but I would also like to suggest that a much cleaner way of doing this is to instead of explicitly redirecting, you set the success page as the action attribute of the form (i.e. <form action="/success.html">) and rather than redirecting when the form is valid, you run event.preventDefault() only when the form is invalid. That's the proper way of working with forms, utilizing the default behavior as much as possible.

此外,提示:如果您想获得更高的JS作业成绩,请使用

Also, pro-tip: if you want to get a higher grade on your JS assignment, use addEventListener() to add your event listeners instead of adding them as inline attributes in the HTML.

这篇关于无法使用javascript重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆