dpnfjx755573 2018-09-12 19:43
浏览 73
已采纳

如何加载更多关于帖子ID的ajax数据,用php获取

  1. I have a "img_title" list. The 'img_title' getting fetched via php from database - dynamic list.

    +------------------------+
    | img_title:             |
    +========================+
    | golden Retriever       |
    +------------------------+
    | Appenzeller Sennenhund |
    +------------------------+
    | German Shepard         |
    +------------------------+
    | Alaskan Klee Kai       |
    +------------------------+
    |       . . . . .        |
    +------------------------+
    
  2. If the user clicks on a "img_title" ...

    +-----------------------------+
    |<b>Appenzeller Sennenhund</b>|     
    +-----------------------------+
    
  3. ... then should show up a new div box with the "img_descr" separately and fetched via AJAX:

    +-----------------------------+     +-----------------------------+
    |   Appenzeller Sennenhund    |     |<b>Swiss: ABC123...      </b>| 
    +-----------------------------+     +-----------------------------+ 
    

    ... or

    +-----------------------------+     +-----------------------------+
    |   golden Retriever          |     |<b>UK: ZYX987...         </b>|
    +-----------------------------+     +-----------------------------+
    

I need a connection between the php fetched data and the ajax fetched data.

I only know how to fetch all description at once but not how to fetch "img_title - ID:3" (php) with only "img_descr - ID:3" (ajax).

I thought about to fetch also the "img_id" and refering to that, ajax could fetch more data from database.

Here is my code (without img_id connection between php & ajax fetched data)

HTML & PHP:

<body>

  <?php
     $db     = mysqli_connect("localhost", "root", "", "xy");
     $result = mysqli_query($db, "SELECT * FROM images");
     while ($row = mysqli_fetch_array($result))
     {
        echo "<button class='img_title'>Title: <b>" . $row['img_title'] . "</b></button><br>";
     }
   ?>

   <div id="descrs"></div>

</body>     

JavaScrpit & AJAX

 <script>
   // Get the buttons (NodeList)
   var buttons = document.querySelectorAll("button.img_title");

   for(var x=0; x < buttons.length; x++) {
     buttons[x].addEventListener('click', loadDescr);
   }

 function loadDescr(e)
 {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'ajax.php', true);

    xhr.onload = function()
    {
       if (this.status == 200)
       {
         var descrs = JSON.parse(this.responseText);

         var output = '';

         for (var i in descrs) {
           output += '<ul>' +
               '<li class="ajax_img_descr">ID: ' + descrs[i].img_descr + '</li>' +  '</ul>';
         }

         document.getElementById('descrs').innerHTML = output;
     }
   }
   xhr.send();
 }
</script>

ajax.php

<?php
// Create Connection
$conn = mysqli_connect('localhost', 'root', '', 'xy');
$query = 'SELECT * FROM images';
// Get Result
$result = mysqli_query($conn, $query);
// Fetch Data
$users = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($users);
?>
  • 写回答

1条回答 默认 最新

  • douyi9597 2018-09-12 20:11
    关注

    As you need to pass ID to server, you somehow should store it in a button, the simpliest way is to use data-attribute:

     while ($row = mysqli_fetch_array($result))
     {
        echo "<button class='img_title' data-id='" . $row['id'] . "'>Title: <b>" . $row['img_title'] . "</b></button><br>";
     }
    

    Next, you have to get this data-id in event handler. It can be done via getAttribute function:

    function loadDescr(e)
    {
        var id = e.target.getAttribute('data-id');
        // console.log(id);    // for testing purposes
    
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'ajax.php?id=' + id, true);
    
        // more codes
    
    }
    

    On serverside your id is available via $_GET['id']:

    <?php
    // Create Connection
    $conn = mysqli_connect('localhost', 'root', '', 'xy');
    $query = 'SELECT * FROM images WHERE id = ' . $_GET['id']; // I simplified this code, but you MUST use prepared statements here to avoid sql-injection
    // Get Result
    $result = mysqli_query($conn, $query);
    // Fetch Data
    $users = mysqli_fetch_all($result, MYSQLI_ASSOC);
    echo json_encode($users);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?