簡體   English   中英

來自 ajax 調用的 JSON 輸入意外結束

[英]Unexpected end of JSON input from an ajax call

我一直在我的項目中研究刪除帖子功能。 在 PHP 中一切正常,但現在我想在 Ajax 中這樣做,以防止刷新等等。

無論如何,當我執行 ajax 調用時,出現錯誤:

SyntaxError: Unexpected end of JSON input
at Object.parse (native)
at n.parseJSON (http://localhost/imdstagram/public/js/jquery-2.2.3.min.js:4:6401)
at Ab (http://localhost/imdstagram/public/js/jquery-2.2.3.min.js:4:8347)
at z (http://localhost/imdstagram/public/js/jquery-2.2.3.min.js:4:11804)
at XMLHttpRequest.<anonymous> (http://localhost/imdstagram/public/js/jquery-2.2.3.min.js:4:15680)

它說這個錯誤在第 35 行,第 35 行將我發送到

console.log(error);

無論如何,為了讓您更好地了解,這是我的 Ajax 調用:

$(document).ready(function(){

    $(".post__delete").on("click", function(e){
        var postDeleteID = $('.deleteID').val();

        $.ajax({
            url: "ajax/deletePost.php", 
            type: "POST",             
            data: JSON.stringify(postDeleteID),
            dataType: 'json',
            contentType: false,
            cache: false,
            processData: false,
            success: function(data)
            {

            },
            error: function (request, status, error) {
                console.log(error);
            }
        });

        e.preventDefault();
    });
});

還有我的 deletePost.php 代碼:

<?php
    include_once("../classes/Post.class.php");
    session_start();
    $post = new Post();

    if(!empty($_POST)){
        $deletePostID = $_POST['deletePostID'];

        $post->deletePost($deletePostID);

        if($post->deletePost($deletePostID)){
            $status['delete'] = "success";
        } else {
            $status['delete'] = "failed";
        }

        header('Content-Type: application/json; charset=utf-8', true);
        echo json_encode($status);
    }

?>

我嘗試了很多事情,比如更改 dataType 和 contentType,但似乎沒有任何效果。

您的請求是錯誤的,如果您希望使用 $_POST 超級全局,則不應發送 json。 將其作為常規 url 編碼的表單數據發送

    $.ajax({
        url: "ajax/deletePost.php", 
        type: "POST",             
        data: {postDeleteID: postDeleteID},
        dataType: 'json',
        cache: false,
        success: function(data)
        {

        },
        error: function (request, status, error) {
            console.log(error);
        }
    });

嘗試將 dataType 更改為 'text' 並將 contentType 更改為 'application/json'

您“刪除”了兩次帖子。

刪除這一行: $post->deletePost($deletePostID);

一般來說,這是框架和 PHP 中一個非常奇怪的問題,在您的控制器中:

echo(json_encode($status));

對我有用..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM