如何在没有php的情况下添加验证码?

时间:2016-02-18 08:22:30

标签: javascript html captcha

这是我的代码:函数check()正在运行,但函数ChangeCaptcha()未在输入type="randomfield"中显示字母:

<body onload="ChangeCaptcha()">
  <input type="text" id="randomfield" disabled><br><br>                               
    <input id="CaptchaEnter" size="20" ><br><br>                         
    <button type="submit" onclick="check()">Log in</button>

  <script type="text/javascript">
    function ChangeCaptcha() {
      var chars= "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
      var string_lenght = 6;
      var ChangeCaptcha = '';
      for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        ChangeCaptcha+= chars.substring(rnum, rnum+1);
      }
      document.getElementById('randomfield').value= ChangeCaptcha;
    }
    function check() {
      if (document.getElementById('CaptchaEnter').value == document.getElementById('randomfield').value) {
        window.open('http://www.lolila.hol.es', '_self');
      } else {
        alert('Pleace re-check the captcha!')
      }
    }
  </script>
</body>

1 个答案:

答案 0 :(得分:1)

我在Chrome开发者控制台中执行了您的代码: enter image description here

它告诉我你的代码中有拼写错误,因为我不知道变量:string_length。你宣称它是string_lenght。要修复,请更改string_lenght =&gt;字符串长度。

结果:

function ChangeCaptcha() {
      var chars= "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
      var string_length = 6;
      var ChangeCaptcha = '';
      for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        ChangeCaptcha+= chars.substring(rnum, rnum+1);
      }
      document.getElementById('randomfield').value= ChangeCaptcha;
    }

结果: enter image description here