【问题标题】:Ajax jQuery on success how to get the result value passed by PHPAjax jQuery 上成功如何获取 PHP 传递的结果值
【发布时间】:2018-01-18 05:34:19
【问题描述】:

如何在 Ajax 上获得成功(数据)价值?我想获取firstname和lastname的值,分别是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();
}

控制台日志结果:

【问题讨论】:

  • 成功循环通过响应并使用密钥获取值

标签: javascript php jquery ajax


【解决方案1】:

1.在$.ajax中添加dataType:"JSON",,使其自动解析来自phpjson数据。

2.Inside 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
    }

});

【讨论】:

  • 谢谢,您的解决方案是更有效的使用方式。
  • @TommyChong 很高兴为您提供帮助:):)
【解决方案2】:
$.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);
    }
});

你会得到数组的对象作为响应

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 2017-01-21
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多