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);
    ?>
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题