成功的Ajax jQuery if语句double json_encode返回欠定值

时间:2018-01-25 04:07:35

标签: javascript php jquery

我试图获取 $ comments_id,$ comments_timestamp,$ user_firstname,$ user_lastname 值并传回给ajax,但是在if语句中只执行了一个 ['的对象数组success-submit-comment'] = true;

的Ajax

$.ajax({
        type:'post',
        url:'getcomment_detail.php',
        data:{comment_id: comment_id,user_desc:user_desc},
        cache:false,
        dataType:'json',
        success: function (data){
            console.log(data);
            var ttes1 = data.comments_timestamp;
            alert(ttes1);


       }
});

getcomment_detail.php

$u_id = $_SESSION['u_id'];
$submit_comment_status = array();

if($sql = "INSERT INTO comments (post_id, user_id, user_desc) VALUES ('$comment_id','$u_id','$user_desc')"){
        mysqli_query($conn,$sql);
        mysqli_close($conn);

        $get_comment_user_detail = "SELECT comments.id, comments.timestamp, user.firstname, user.lastname FROM comments INNER JOIN user ON user.id = comments.user_id WHERE user.id = $u_id ORDER BY comments.id DESC LIMIT 1";

        if($stmt = $conn->prepare($get_comment_user_detail)) {

            $stmt->execute();

            $stmt->bind_result($comments_id, $comments_timestamp, $user_firstname, $user_lastname);

            while ($stmt->fetch()) {

                $comments_userdetails = array(
                    'comments_id' => $comments_id,
                    'comments_timestamp' => $comments_timestamp,
                    'u_firstname' => $user_firstname,
                    'u_lastname' => $user_lastname
                );

                header('Content-Type: application/json');
                echo json_encode($comments_userdetails);
            }
            $stmt->close();
        }

        $submit_comment_status['successful-submit-comment'] = true;
        header('Content-Type: application/json');
        echo json_encode($submit_comment_status);
    }

控制台返回值:

enter image description here

警报返回值:

未定义

1 个答案:

答案 0 :(得分:1)

为什么不把它放入数组并将其全部作为json文件返回?

$comments_userdetails = array(
                'comments_id' => $comments_id,
                'comments_timestamp' => $comments_timestamp,
                'u_firstname' => $user_firstname,
                'u_lastname' => $user_lastname,
                'successful-submit-comment' => true
            );

            header('Content-Type: application/json');
            echo json_encode($comments_userdetails);

在您的ajax中,您只需获得类似

的值
console.log(data['successful-submit-comment']);