繁体   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