簡體   English   中英

jQuery成功的Ajax如何獲取PHP傳遞的結果值

[英]Ajax jQuery on success how to get the result value passed by PHP

如何在Ajax上獲得成功(數據)值? 我想獲取名字和姓氏的值,即Kevin Yam。

示例我想設置輸入值document.getElementById("reply").value = "Kevin Yam"

Ajax代碼:

$.ajax({
    type:'post',
    url:'getuser_reply_name.php',
    data:{get_reply_postid:post_id,get_reply_commentid:comment_id},
    cache:false,
    success: function (data){
        console.log(data);
    }
});

getuser_reply_name.php代碼:

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

    $stmt->execute();

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

        while ($stmt->fetch()) {

            $userdetails = array(
                'u_firstname' => $user_firstname,
                'u_lastname' => $user_lastname
            );

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

控制台日志結果:

在此處輸入圖片說明

1.在$.ajax添加dataType:"JSON",以便它自動解析來自php json數據。

2. success使用keys從響應中獲取數據(在console.log()中看到的內容)

像下面這樣:

$.ajax({
    type:'post',
    url:'getuser_reply_name.php',
    data:{get_reply_postid:post_id,get_reply_commentid:comment_id},
    dataType:'json', //add dataType
    cache:false,
    success: function (data){
        $("#reply").val(data.u_firstname+' '+data.u_lastname); // put value to input box
    }

});
$.ajax({
    type:'post',
    url:'getuser_reply_name.php',
    data:{get_reply_postid:post_id,get_reply_commentid:comment_id},
    cache:false,
    dataType: 'json', // what type of data do we expect back from the server
      encode: true,
    success: function (data){
        console.log(data);
    }
});

您將獲得數組對象作為響應

暫無
暫無

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

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