douruanfan3030 2013-01-16 06:22
浏览 45
已采纳

奇怪的jQuery AJAX成功函数行为

I have a PHP contact form that I'm using with jQuery's AJAX method, but I'm getting very strange results with the "success:" function.

Here's the PHP contact form:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$message = $_POST['message'];
$msg = "Name: $name
";
$msg .= "Email: $email
";
$msg .= "Number: $number

";
$msg .= "$message
";
$recipient = "[recipients here]";
$subject = "Contact Us - $name";
$mailheaders = "From:$email";
$success = mail($recipient, $subject, $msg, $mailheaders);

if ($success) {
    echo ('Correct');
} else {
    echo ('Failed');
}
header("Location: [website address here]");
?> 

Here's the jQuery AJAX method:

$("#contact-form").submit(function (event) {
    $.ajax({
        type: "POST",
        url: '/lib/mailer.php',
        data: {
            name: $("#name").val(),
            email: $("#email").val(),
            number: $("#number").val(),
            message: $("#message").val()
        },
        success: function (data) {
            //$("#contact-form")[0].reset();
            alert(data);

            if(data === 'Correct') {
                alert('Data is correct');
            }
            else if (data !== 'Correct') {
                alert('Data is not equal to correct');
            }
            else {
                alert('Else statement');
            }
        }
    });

    event.preventDefault();
    return false;
});

Now, when I fill in the form and click submit, the PHP receives the right data and successfully sends the email, and echo's "Correct". An alert pops up saying "Correct". But then, instead of the next alert being "Data is correct", it is "Data is not equal to correct".

I have no idea what's going on here for that to happen. I'm assuming I must be making a really stupid mistake somewhere but can't seem to figure it out.

  • 写回答

3条回答 默认 最新

  • dtncv04228 2013-01-16 06:31
    关注

    It is not matching the word. Use

    if($.trim(data) == 'Correct')
    

    Hope it will help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划