简体   繁体   English

jQuery成功的Ajax如何获取PHP传递的结果值

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

How I can get the success (data) value on Ajax? 如何在Ajax上获得成功(数据)值? I want to get the value of firstname and lastname, which are Kevin Yam. 我想获取名字和姓氏的值,即Kevin Yam。

Example I want to set input value, document.getElementById("reply").value = "Kevin Yam" 示例我想设置输入值document.getElementById("reply").value = "Kevin Yam"

Ajax code: 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 code: 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();
}

Console log result: 控制台日志结果:

在此处输入图片说明

1.Add dataType:"JSON", in your $.ajax , so that it automatically parse json data coming from php . 1.在$.ajax添加dataType:"JSON",以便它自动解析来自php json数据。

2.Inside success fetch data from response using keys (what you are seeing in console.log() ) 2. success使用keys从响应中获取数据(在console.log()中看到的内容)

Do like below:- 像下面这样:

$.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);
    }
});

you will get object of array in response 您将获得数组对象作为响应

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM