反垃圾邮件脚本由于某种原因没有检测到变量(我从中得到了什么)

时间:2013-03-18 19:51:41

标签: javascript jquery

function commentpost(){
  var allow = true;
  var game = "<?php echo $game ?>";
  var name = $("input#name").val();
  var comment = $("textarea#comment").val();
  var date =  currentdate();
  var dataString = "postdate=" + date + "&game=" + game + "&name=" + name + "&comment=" + comment;
  if(name && comment && allow){
    $.ajax({
      type: "POST",
      url: "../php/addcomment.php",
      data: dataString,
      success: function(){
        updatecomments();
        //important part here V
        allow = false;
        setTimeout(function(){
          allow = true; 
          // alert(allow);
        }, 5000);
        // alert(allow);
        //important part here ^
      }
    });
  }
  //important part here V
  else if ((!name || !comment) && allow){
    alert("Please fill out both the Name and Comment fields");
  }
  else if (!allow){
    alert("Commenting has been limited to 5 seconds in between to pevent spamming.");
  }
  //important part here ^
}

我在我正在创建的网站上有一个小的基本评论脚本。一切正常,但我试图阻止提交按钮被垃圾邮件。这似乎应该对我有用,但由于某种原因它不是,我想某种方式是由于我使用“允许”的方式。

1 个答案:

答案 0 :(得分:0)

你的allow变量有一个范围问题:你重新创建它并在每次调用commentPost()时将其设置为true,所以当你检查它的值时它总是为真。

你需要这样的东西:

var allow = true;

function commentpost(){
  //...
  if(name && comment && allow){
    $.ajax({
      type: "POST",
      url: "../php/addcomment.php",
      data: dataString,
      success: function(){
        updatecomments();
        allow = false;
        setTimeout(function(){
          allow = true; 
        }, 5000);
      }
    });
  }

当然,我不建议全局声明允许,但是如果不知道评论信息的上下文,就很难说它应该存储在哪里。