dsyk33753 2013-04-29 12:45
浏览 67
已采纳

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

Today I need some help concerning one of my work. I'm trying to display, in JQuery, some data I retrieved, in PHP, from my database.

I need to display the data in JQuery for some reasons...

My PHP and my JQuery are on the same page, index.php, but my problem is that my ajax won't display my data and no error appears so I don't know exactly where is my mistake.

Here is my code:

<?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>

So when I load my page, my JQuery does the "console.log('Failed to load data')" which means there is an error but I can't find it.

Somebody can help me please ?

Thnx, Antho

EDIT 1:

It seems there is no problem with my PHP request because the echo display the data I retrieve from the database. Apparently the error comes from my ajax request.

I've set the URL parameters on 'index.php' but doesn't work neither.

EDIT 2:

After some researches it seems impossible to make a PHP request and an ajax request on the same page. So I'll try something else...

  • 写回答

2条回答 默认 最新

  • douju1365 2013-04-29 13:23
    关注

    What you are currently doing is this:

    you are creating an output that looks like this:

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

    Now there are multiple problems.

    • There is json before the html output
    • there is an ajax call that tries to get the file you just outputted, but there is html after the json, so it does not understand the json

    To fix this you could put it in 2 different files.

    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>
    

    or you could put it in one file and use conditions to split it up

    <?
    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'"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛