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";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效