AJAX按钮没有提交,也没有通过

AJAX button not submitting and not going through

本文关键字:提交 按钮 AJAX      更新时间:2023-09-26

我遇到一个问题,我的Ajax代码无法通过。。就好像函数是空的一样。我点击了提交,什么也没发生。。

我的HTML代码:

<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<body>
<form method="POST" id="contactForm" >
<input type="text" name="email" id="email"></input>
<input type="submit" name="submit"></input>
</form>
<script type="text/javascript">
$('#contactForm').submit(function(e){
    e.preventDefault();
    var email = $('#email').val();
    $.ajax({
        type: 'POST',
        dataType: 'JSON',
        url: 'check.php',
        data: {email: email},
        success: function(data){
            if(data.status == 'success') {
                alert('The e-mail address entered is correct.');
            } else {
                alert('The e-mail address entered is Incorrect.');
            }
        }
    });
});
</script>
</body>
</head>

我的支票.php:

  <?php
if (isset($_POST['email'])) {
    $status = 'success'
} else {
    $status = 'failed';
}
echo json_encode(array('status' => $status));
?>

当我点击提交时,它什么也不做。。我想弹出错误。

我错过了什么吗?

请确保传递到ajax调用的所有选项都有正确的大小写。示例:数据类型需要变为datatype,beforesend需要变为beforesend。

以下是参考资料:http://api.jquery.com/jquery.ajax/

括号放错了位置,您缺少一个表示"success"回调的:。参见下面的固定代码,

这里的另一个答案中也提到了这种情况。。

$('#contactForm').submit(function () {
    var email = $('#email').val();
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: 'check.php',
        beforeSend: function () {},
        //     v--- missing :
        success: function (data) {
            if (data.status == 'success') {
                alert('The e-mail address entered is correct.');
            } else if (data.status !== 'success') {
                alert('The e-mail address entered is wrong.');
            }
        } // this was misplaced in the line below in your code
    }); // this was misplaced in the line above in your code
});

尝试使用Firefox或Chrome的开发工具进行调试。

在Chrome的DevTools上,例如:

  • 使用source选项调试Javascript。或者在.submit()函数中冷添加一些console.log(),以确保事件处理程序正在触发
  • 使用"网络"选项卡确保正在进行ajax调用,并检查您从服务器得到的响应
  • 最后但同样重要的是,检查控制台选项卡中的Javascript错误,看看在执行脚本之前是否有其他脚本抛出错误

有了这些技术,您可以确定可能出现的问题,并了解如何解决。