在 PHP 中从数据库中检索数据并在同一页面上的 JQuery 中显示它们

Posted

技术标签:

【中文标题】在 PHP 中从数据库中检索数据并在同一页面上的 JQuery 中显示它们【英文标题】:Retrieve data from database in PHP and display them in JQuery on the same page 【发布时间】:2013-04-23 03:20:16 【问题描述】:

今天我需要一些关于我的一项工作的帮助。我试图在 JQuery 中显示我在 php 中从我的数据库中检索到的一些数据。

由于某些原因,我需要在 JQuery 中显示数据...

我的 PHP 和我的 JQuery 在同一个页面index.php,但我的问题是 我的 ajax 不会显示我的数据 strong> 并且没有出现错误,所以我不知道我的错误到底在哪里。

这是我的代码:

<?php
    require 'inc/db-connect.php';

    $title = array();

    try
        $sql   = "SELECT * FROM events";
        $req   = $db->query($sql);  
    catch(PDOException $e)
        echo 'Erreur: '.$e->getMessage();
    

    while($res = $req->fetch())
        array_push($title, $res['title']);
    

    echo json_encode($title);

    $req->closeCursor();
?>

<!DOCTYPE html>

<html lang="fr">
    <?php include('inc/head.html'); ?>

    <body>
        <div id="stage">

            /** 
            * ALL MY HTML GOES HERE 
            **/

        </div>
        <!-- END STAGE -->

        <script type="text/javascript">
            $(document).ready(function()
                $.ajax(
                    data: "",
                    dataType: 'json',
                    success: function(data)
                        console.log(data);
                    ,
                    error: function()
                        console.log('Failed to load data');   
                    
                );
            );
        </script>
    </body>
</html>

所以当我加载我的页面时,我的 JQuery 会执行 "console.log('Failed to load data')",这意味着有错误但我找不到。 p>

有人可以帮助我吗?

谢谢, 安托

编辑 1:

我的 PHP 请求似乎没有问题,因为 echo 显示了我从数据库中检索到的数据。显然错误来自我的 ajax 请求。

我已经在 'index.php' 上设置了 URL 参数,但也没有用。

编辑 2:

经过一些研究,似乎不可能在同一页面上发出 PHP 请求和 ajax 请求。所以我会尝试其他的...

【问题讨论】:

在您的浏览器中单击鼠标右键并查看您的脚本生成的源代码。您应该立即发现问题。 这令人困惑。 $.ajax 没有要获取的 url。 ajax 函数中的 URL 选项在哪里?这是否可以在不传入 URL 的情况下获取数据? 我在这篇文章中读到,如果我在同一页面上执行我的 ajax 请求,我可以让 url 参数为空。 ***.com/questions/7561569/… 我尝试将 url 参数设置为 'index.php' 但这也不起作用:\. @nvanesch - 是的,PHP 和 JQuery 在同一个文件中。 【参考方案1】:

你目前正在做的是:

您正在创建一个如下所示的输出:

"your json is": "here"
<html>
  ... rest of html
  <script> doing an ajax request to get the json </script>
  ...
</html>

现在有多个问题。

html输出前有json 有一个 ajax 调用试图获取您刚刚输出的文件, 但是json后面有html,所以看不懂json

要解决此问题,您可以将其放入 2 个不同的文件中。

getmyjson.php

<?php
    require 'inc/db-connect.php';

    $title = array();

    try
        $sql   = "SELECT * FROM events";
        $req   = $db->query($sql);  
    catch(PDOException $e)
        echo 'Erreur: '.$e->getMessage();
    

    while($res = $req->fetch())
        array_push($title, $res['title']);
    

    header('Content-type: application/json');
    echo json_encode($title);

    $req->closeCursor();
    exit();

index.php

<html lang="fr">
    <?php include('inc/head.html'); ?>

    <body>
        <div id="stage">

            /** 
            * ALL MY HTML GOES HERE 
            **/

        </div>
        <!-- END STAGE -->

        <script type="text/javascript">
            $(document).ready(function()
                $.ajax(
                    url: "getmyjson.php"
                    data: "",
                    dataType: 'json',
                    success: function(data)
                        console.log(data);
                    ,
                    error: function()
                        console.log('Failed to load data');   
                    
                );
            );
        </script>
    </body>
</html>

或者您可以将其放在一个文件中并使用条件将其拆分

<?
if(isset($_GET['getmyjson']))

  // output json (incl header)
  exit();

else // why an else when you already did an exit.. just to be safe when you or someone else is modifying the code

  // output your main page with the ajax script that calls "url: '?getmyjson=true'"

【讨论】:

谢谢!确实,有 2 个不同的文件就没有问题了;)。【参考方案2】:

将内容的头部设置为json类型...这里是设置头部类型的示例。

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

任何格式错误的 JSON 都会被拒绝并引发解析错误。

【讨论】:

显然错误来自我的 ajax 请求,因为 PHP 回显显示了我应该检索到的数据。

以上是关于在 PHP 中从数据库中检索数据并在同一页面上的 JQuery 中显示它们的主要内容,如果未能解决你的问题,请参考以下文章