drix47193
2019-04-21 21:36
浏览 229
已采纳

始终在pushJsonData中收到错误:parsererror:SyntaxError:我脚本中JSON输入[object Object]的意外结束

I always receive the Parser error in pushJsonData and I don't know why.

I tested it first with just the user value and it works fine, but when I try to thrwo back mor than the user I recieve the error below:

SyntaxError: Unexpected end of JSON input [object Object]

My JavaScript code:

$('#Login').click(function() {
    var user = $("#user").val();
    $.ajax({
        url: "src/ajax.php",
        type: "POST",
        data: { ACTION : "checkUser", USER: user},
        dataType: "json",
        success: function(data)  {
            var user = data.user;
            $('#testUser').text("Hallo " + user);
        },

        error: function(jqXHR, textStatus, errorThrown) {
            alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR);
        }
    });
});

My PHP code:

if($_POST['ACTION'] == "checkUser") {
    $checkUser      = $_POST['USER'];
    $sql            = $db->query("SELECT * FROM fm_user WHERE user = '".$checkUser."' LIMIT 1");
    $getUser        = $sql->fetch_assoc();

    $resultArray    = array(
                        "user" => $getUser['user'],
                        "isadmin" => $getUser['isadmin'],
                        "user_data" => $getUser['user_data']
                    );

    $result = json_encode($resultArray);
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drduh44480 2019-04-21 22:02
    已采纳

    You're not outputting anything. But, rather than close this as off-topic due to a typo I wanted to point out some issues with your code, which is unsafe and inefficient. Always always use prepared statements, and there's no need to waste code putting array elements into an array. Something like this should work better:

    <?php
    if($_POST['ACTION'] == "checkUser") {
        $result = null;
        $checkUser = $_POST['USER'];
        $stmt = $db->prepare("SELECT user, isadmin, user_data FROM fm_user WHERE user = ? LIMIT 1");
        $stmt->bind_param("s", $checkUser);
        if ($stmt->execute()) {
            $result = $stmt->get_result();
            $getUser = $result->fetch_assoc();
    
            $result = $getUser;
        }
        header("Content-Type: application/json");
        echo json_encode($result);
        die();
    }
    

    Untested, and it's been a long time since I've used mysqli but it should work.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题