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条)

报告相同问题?

悬赏问题

  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路