在输入字段中存储JSON值

时间:2017-08-31 23:34:12

标签: php jquery html mysql ajax

嗨,我正在寻求帮助

我正在学习如何使用Ajax和PHP,我想要做的是在PHP中运行查询并将结果存储在JSON中。
然后我想要echo JSON并将其值设置为文本字段。

这可能吗?

因为我是Ajax和jQuery的新手,所以我不知道如何做到这一点 我试图这样做,但我只得到数组的第一个值。

这是我的代码:

    <input type="text" id="text1">
    <button type="button" class="btn btn-success" id="send">Success Button</button>
    <input type="text" id="text2">
    <input type="text" id="text3">
    <input type="text" id="text4">


  <script type="text/javascript">
  $(document).ready(function(){
    $("#send").click(function(event){
      event.preventDefault();
      var Rfc=$("#text1").val();

      $.ajax({
        type: 'POST',
        url: 'search.php',
        data: 'Rfc='+Rfc,
        dataType : 'json',
        success: function(msg){
          var datashow = JSON.parse(msg);
          $("#text2").val(msg[0].id_person); ///this is the only value that i get
          $("#text3").val([1].person_name); ///i want to get the person's name here
          $("#text4").val([2].person_address);///i want to get the person's address here
        },
        error : function () {
          alert("error");
        }
      });
    });
  });
  </script>

这是我的PHP文件:

<?php 

$rfc=$_POST['Rfc'];

$connection = mysqli_connect("localhost","root","","transferorders");
$query = mysqli_query($connection,"SELECT * FROM person where rfc_number ='$rfc'");
$Data = array();

while($row = mysqli_fetch_assoc($query)){
  $Data[]=$row;
  echo json_encode($Data);   
}

?>

这是我在控制台中得到的

未捕获的TypeError:无法读取未定义的属性“person_name”     在Object.success(测试ajax1.php:40)

1 个答案:

答案 0 :(得分:0)

PHP文件中的php尝试识别数组中的每个变量以在脚本中捕获它们,看看这个:

<?php 

$rfc=$_POST['Rfc'];

$connection = mysqli_connect("localhost","root","","transferorders");
$query = mysqli_query($connection,"SELECT * FROM person where rfc_number ='$rfc'");

$row = mysqli_fetch_array($query)

    $Data = '{"id":"'.$row['id_person'].'", "name":"'.$row['person_name'].'", "address":"'.$row['person_address'].'"}';

    echo json_encode($Data);

?>

和脚本:

success: function(msg){
          var datashow = JSON.parse(msg);
          $("#text2").val(datashow["id"]); ///this is the only value that i get
          $("#text3").val(datashow["name"]); ///i want to get the person's name here
          $("#text4").val(datashow["address"]);///i want to get the person's address here
        },

我希望它有所帮助!