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条回答 默认 最新

相关推荐 更多相似问题