【问题标题】:if function not being triggered although result variable has the correct value in it如果函数没有被触发,尽管结果变量中有正确的值
【发布时间】:2012-07-15 04:11:18
【问题描述】:

所以我正在写这个订阅页面..当用户点击提交时,它应该将电子邮件发送到数据库..我使用 jQuery 的 post 方法,所以在提交时应该返回 send 的结果,如果这是真的,按钮应该消失,并且应该出现一条发送的消息,但是当我使用 console.log 打印结果值它说成功但 if 语句将转到 else 子句并打印错误消息时,这并没有发生。

$.post("send_email.php", $("#contact_form").serialize(),function(result){
    console.log(result);
    //and after the ajax request ends we check       the text returned
    if(result == "sent"){

        //if the mail is sent remove the submit paragraph
        $('#button').remove();
        //and show the mail success div with fadeIn
        $('#mail_success').fadeIn(500);
    }else{
        console.log('going to failure clause');
        //show the mail failed div
        $('#mail_fail').fadeIn(500);
        //reenable the submit button by removing attribute disabled and change the text back to Send The Message
        $('#send_message').removeAttr('disabled').attr('value', 'Submit');
    }
});

【问题讨论】:

  • 您确定result 不包含任何空格吗?如果确实如此,那么修复它的地方将在您的 PHP 中,但假设如果您不控制 PHP,您可以更改您的 if 条件以允许空白,也许:if (result.replace(/\s/g,"") === "sent") {...
  • 是的,它不起作用 success() { die ("sent"); }//结束成功函数
  • 我使用了 if (result.replace(/\s/g,"") === "sent") {... 来允许空格并修复它感谢 nnnnn。感谢其他所有人的贡献
  • 好的,很酷,我已经发布了我的评论作为答案。

标签: php jquery post if-statement subscription


【解决方案1】:

当我使用 console.log 打印结果值时,它显示成功

所以,这不是吗:

                    if(result == "sent"){

需要这样:

                    if(result == "success"){

?

【讨论】:

    【解决方案2】:

    我的猜测是您的 PHP 响应包含在您登录 result 时不明显的空白。如果由于某种原因无法在 PHP 代码中修复,那么您可以更新您的 JS if 条件以忽略空格,如下所示:

    if (result.replace(/\s/g,"") === "sent") {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多