php - 在输入字段中存储 JSON 值

标签 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);   
}

?>

这是我在控制台中得到的

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

最佳答案

兄弟在 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
        },

希望对您有帮助!

关于php - 在输入字段中存储 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45991480/

相关文章:

javascript - 整合 $.ajax

html - 固定居中的粘性页脚无法定位在中心..请提供想法

php - MySQL SELECT 与 IF 语句从另一个表设置变量

php - 在 PHP 中包含不同类型的文件

javascript - 链接无法在新窗口中打开

jquery - 从 jQuery 中的 GridView HTML 获取文本以应用 CSS

javascript - 按钮应该仅在两个事件后可用

html - 停止覆盖以前的 CSS 属性

php - 在我的插入代码部分出现 SQL 语法错误

PHP 检查数组中的多个值 - 正确的方法?