doumindang2416 2015-06-23 19:22
浏览 45
已采纳

如何使用AJAX和JSON获取从PHP文件返回的数据

For starters this website is being run on a Debian machine. I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.

Here is the PHP code to get the information from the database:

<?php

class MyDB extends SQLite3
{
    function __construct()
    {
        $this->open('website.db');
    }
}

$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>

Here is the JavaScript where the AJAX is located:

<script type="text/javascript">

 function getNews()
 {
     console.log("firstStep");
      $(document).ready(function()
      {

        console.log("secondStep");
        $.getJSON("http://localhost/getNews.php",function(result){

            console.log("thirdStep");
            $('news').append(result); // display result

                 });
       });
  }

I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.

This is the HTML it should be appending to: <div id = "newsEntry"> <news> test </news> </div>

Any help would be appreciated.

  • 写回答

2条回答 默认 最新

  • duandou2763 2015-06-23 19:44
    关注

    To find out what's going on, you might want to add an error handler:

    $(document).ready(function() {
      $.ajax({
        url: "http://localhost/getNews.php",
        dataType: "json",
        success: function(result) {
          console.log("thirdStep");
        },
        error: function(err) {
          alert(err);
        }
      });
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?