jquery .ajax 总是返回错误 - 数据被添加到数据库中


jquery .ajax always returns error - data being added to database

我正在尝试使用 jquery ajax 调用将用户添加到数据库中。用户被很好地添加到数据库中,但 ajax 总是返回错误。我也不确定如何检索特定错误。下面是我的代码,表单,php和jquery。

这是jquery

$(document).ready(function() {
    //ajax call for all forms. 
    $('.button').click(function() {
        var form = $(this).closest('form');
        $.ajax({
            type: "POST",
            url: form.attr('data'),
            dataType: 'json',
            data: form.serialize(),
            success: function (response) {
                alert('something');
            },
            error: function() {
                alert('fail');
            }
        });
    });
  });

这是 PHP

<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
    $user = new Users;
    $user->cleanInput($_POST['username'], $_POST['password']);
    if($user->insertUser()) {
        echo json_encode('true');
    } else {
        echo json_encode('false');
    }
}

这是 HTML

<div id='newUser' class='tool'>
    <h3>New User</h3>
    <form method='post' name='newUser' data='../php/newUser.php'>
        <span>Username</span><input type='text' name='username'><br>
        <span>Password</span><input type='password' name='password'>
        <input type='submit' name='submit' class='button' style='visibility: hidden'>
    </form>
    <span class='result'> </span>
</div>

> @Musa,上面你提到

我的猜测是这是一个解析错误,请尝试删除数据类型:"json",看看它是否有效

你绝对解决了我遇到的问题!我的 ajax post 请求与上面类似,它只是不断返回到"错误"部分。虽然我使用Firebug进行了检查,但状态为200(ok),没有错误。

删除"数据类型:json"为我解决了这个问题。多谢!

事实证明,我不得不向 $.ajax 函数添加async: false。它没有得到来自 php 的回复。

我知道

这是一个老问题,但我刚刚遇到了这样的奇怪情况(jquery ajax 在直接执行时返回成功,但在附加到按钮时返回错误,即使服务器响应为 200 OK)

并发现将按钮放在form标签内会导致 JQuery 始终返回错误。只需将form标签更改为div就可以解决问题。

我相信 JQuery 假设通信应该是形式编码的,即使你说它是application/json

尝试将按钮移到窗体之外,看看会发生什么...

我在那里遇到了同样的问题和发现。问题一直出在我的jQuery版本上,我使用了jquery版本(jquery-1.10.2.js),但这个版本不是Ajax稳定版。所以,我更改了(jquery-1.8.2.js)的版本,这个奇迹被淹没了。

祝你好运!

应指定状态代码 200 才能成功响应。

<?php
http_response_code(200);
?>

看这里: http://php.net/manual/en/function.http-response-code.php

第一个解决方案

尝试像这样删除 js 文件中的dataType

$(document).ready(function() {
    $('.button').click(function() {
        var form = $(this).closest('form');
        $.ajax({
            type: "POST",
            url: form.attr('data'),
            data: form.serialize(),
            success: function (response) {
                alert('something');
            },
            error: function() {
                alert('fail');
            }
        });
    });
});

第二种解决方案

像这样向AJAX发送一个真正干净的JSON:

.PHP

if(isset($_POST['username'])) {
    $user = new Users;
    $user->cleanInput($_POST['username'], $_POST['password']);
    if($user->insertUser()) {
        $error = [
            "title"=> 'true',
            "body"=> 'some info here ... '
        ];
        echo json_encode($error);
    } else {
        $error = [
            "title"=> 'false',
            "body"=> 'some info here ... '
        ];
        echo json_encode($error);
    }
}

JavaScript

$(document).ready(function() {
    $('.button').click(function() {
        var form = $(this).closest('form');
        $.ajax({
            type: "POST",
            url: form.attr('data'),
            dataType: 'json',
            data: form.serialize(),
            success: function (data) {
                let x = JSON.parse(JSON.stringify(data));
                console.log(x.title);
                console.log(x.body);
            },
            error: function() {
                //code here
            }
        });
    });
});