duanli9001
2018-09-13 13:38
浏览 61
已采纳

如何使用Ajax将变量从PHP发送到javascript?

So I have a PHP file where I fetch the data from the database. I also have a JavaScript file where I make an ajax request. Everything is okay, but I'd like to stop the JSON from going on my web page when I echo it. I just want to work with the JSON in Javascript. Here is my code:

Javascript:

$(document).ready(function() {
  var url = "../../DB/get-data.php";
    $.ajax({
      type: "POST",
      url: url,
      success: function(data){
         var mydata = jQuery.parseJSON(data);
         console.log(mydata);
      }
    });
});

PHP:

$sql = "SELECT * FROM animals ORDER BY age DESC";
$result = $conn->query($sql);
$animals = [];
while($row = $result->fetch_assoc()) {
  $animal = new Animals($row['name'], $row['species'], $row['color'], $row['age']);
  array_push($animals, $animal);
}
echo json_encode($animals);
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyu4863 2018-09-13 13:52
    已采纳

    You could separate the two files, the file that gets the data without the echo :

    get-data.php

    $sql = "SELECT * FROM animals ORDER BY age DESC";
    $result = $conn->query($sql);
    $animals = [];
    while($row = $result->fetch_assoc()) {
      $animal = new Animals($row['name'], $row['species'], $row['color'], $row['age']);
      array_push($animals, $animal);
    }
    

    And another file for the JSON result that implements the echo statement and includes the first one :

    get-data-json.php

    include 'you_path_here/get-data.php';
    
    echo json_encode($animals);
    

    Then the URL variable in your JS code should call the JSON route like :

    var url = "../../DB/get-data-json.php";
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题