douju5933
2018-01-18 05:34
浏览 154

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

How I can get the success (data) value on Ajax? I want to get the value of firstname and lastname, which are Kevin Yam.

Example I want to set input value, document.getElementById("reply").value = "Kevin Yam"

Ajax code:

$.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:

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:

enter image description here

图片转代码服务由CSDN问答提供 功能建议

如何在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( 数据); 
} 
}); 
   
 
 

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 
  ); 
 
标题('Content-Type:application / json'); 
 echo json_encode($ userdetails); 
} 
 $ stmt->  close(); 
} 
   
 
 

控制台日志结果:

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsqdpn31467 2018-01-18 05:38
    已采纳

    1.Add dataType:"JSON", in your $.ajax, so that it automatically parse json data coming from php.

    2.Inside success fetch data from response using keys(what you are seeing in 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
        }
    
    });
    
    打赏 评论
  • dongzhansong5785 2018-01-18 07:51
    $.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

    打赏 评论

相关推荐 更多相似问题