如何在无限滚动中使用AJAX传递帖子ID

huangapple go评论47阅读模式
英文:

How to pass the post id with AJAX in an infinite scroll

问题

我从数据库中获取了15个帖子(在我的情况下是提示),当用户点击其中一个时,通过将ID与URL一起传递,将用户发送到该帖子的详细页面。

示例:
在页面顶部:
$imagesToApprove = Prompt::get15ToApproveImages();

在HTML中:

<?php foreach ($imagesToApprove as $imageToApprove) : ?>
    <a href="promptDetails.php?id=<?php echo $imageToApprove['id'] ?>">
        <img src="<?php echo $imageToApprove['cover_url']; ?>" alt="prompt">
    </a>
<?php endforeach; ?>

现在我想要在具有无限滚动的情况下执行相同的操作,当用户向下滚动时,从数据库中加载新帖子。我使用了AJAX和PHP来实现这一点,但我似乎无法弄清如何传递ID。

HTML:

<main class="flex flex-wrap">
        <div id="image-container" class="flex flex-wrap"></div>
</main>
<script src="ajax/infiniteScrollToApprove.js"></script>

AJAX文件 infiniteScrollToApprove.js:

var offset = 0;
var limit = 20;

// 初始化加载标志
var loading = false;

function loadImages() {
  // 将加载标志设置为true,以防止同时进行多个请求
  loading = true;

  // 创建新的XMLHttpRequest对象
  var xhr = new XMLHttpRequest();

  // 设置请求方法、URL和标头
  xhr.open("POST", "./loadPromptsToApprove.php", true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

  // 处理来自服务器的响应
  xhr.onload = function () {
    if (xhr.status === 200) {
      // 解析JSON响应
      var images = JSON.parse(xhr.responseText);
      console.log("Parsed images:", images);

      // 遍历图像并创建img元素
      if (images.length > 0) {
        for (var i = 0; i < images.length; i++) {
          var img = document.createElement("img");
          img.setAttribute("src", images[i].cover_url);
          img.classList.add("flex", "w-1/4");
          document.getElementById("image-container").appendChild(img);
        }

        // 更新偏移量以跟踪加载的图像数量
        offset += limit;

        // 将加载标志设置为false,以允许进行新的请求
        loading = false;
      } else {
        // 如果没有更多图像可加载,删除滚动事件侦听器,以防止进一步的请求
        window.removeEventListener("scroll", checkScroll);
      }
    }
  };

  // 通过偏移量和限制参数发送带有偏移量和限制参数的AJAX请求
  xhr.send("offset=" + offset + "&limit=" + limit);
}

// 检查用户是否滚动到页面底部的功能
function checkScroll() {
  if (
    window.scrollY + window.innerHeight >=
    document.documentElement.scrollHeight
  ) {
    // 如果用户滚动到页面底部且当前没有加载请求,调用loadImages()函数以获取新图像
    if (!loading) {
      loadImages();
    }
  }
}

// 将滚动事件侦听器附加到窗口对象,以在用户滚动时触发checkScroll()函数
window.addEventListener("scroll", checkScroll);

// 加载初始图像
loadImages();

loadToApprovePrompts:

<?php
include_once("bootstrap.php");

// 开始输出缓冲
ob_start();

// 从POST请求中获取偏移和限制值
$offset = $_POST['offset'];
$limit = $_POST['limit'];

// 使用偏移和限制值从数据库中检索图像数组
$images = Prompt::getAllToApproveImages($offset, $limit);

// 将图像数组编码为JSON对象,并将其作为响应发送回AJAX请求
echo json_encode($images);

// 刷新输出缓冲
ob_end_flush();
英文:

I have 15 posts(prompts in my case) that I get from the database and when a user clicks on one of them he gets sent to a detailpage of that post by giving the id with the url.

example:
on the top of the page: $imagesToApprove = Prompt::get15ToApproveImages();

in the html:

&lt;?php foreach ($imagesToApprove as $imageToApprove) : ?&gt;
    &lt;a href=&quot;promptDetails.php?id=&lt;?php echo $imageToApprove[&#39;id&#39;] ?&gt;&quot;&gt;
        &lt;img src=&quot;&lt;?php echo $imageToApprove[&#39;cover_url&#39;]; ?&gt;&quot; alt=&quot;prompt&quot;&gt;
    &lt;/a&gt;
&lt;?php endforeach; ?&gt;

Now I want to do the same with this infinite scroll that I have where when the user scrolls down new posts get loaded from the database, I did this with AJAX and PHP but I cant't seem to figure out how to give the id with it.

html:

&lt;main class=&quot;flex flex-wrap&quot;&gt;
        &lt;div id=&quot;image-container&quot; class=&quot;flex flex-wrap&quot;&gt;&lt;/div&gt;
&lt;/main&gt;
&lt;script src=&quot;ajax/infiniteScrollToApprove.js&quot;&gt;&lt;/script&gt;

AJAX file infiniteScrollToApprove.js:

var offset = 0;
var limit = 20;

// Initialize loading flag
var loading = false;

function loadImages() {
  // Set loading flag to true to prevent multiple requests from being made simultaneously
  loading = true;

  // Create new XMLHttpRequest object
  var xhr = new XMLHttpRequest();

  // Set request method, URL and headers
  xhr.open(&quot;POST&quot;, &quot;./loadPromptsToApprove.php&quot;, true);
  xhr.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);

  // Handle response from server
  xhr.onload = function () {
    if (xhr.status === 200) {
      // Parse JSON response
      var images = JSON.parse(xhr.responseText);
      console.log(&quot;Parsed images:&quot;, images);

      // Loop through images and create img elements
      if (images.length &gt; 0) {
        for (var i = 0; i &lt; images.length; i++) {
          var img = document.createElement(&quot;img&quot;);
          img.setAttribute(&quot;src&quot;, images[i].cover_url);
          img.classList.add(&quot;flex&quot;, &quot;w-1/4&quot;);
          document.getElementById(&quot;image-container&quot;).appendChild(img);
        }

        // Update offset to keep track of number of images loaded
        offset += limit;

        // Set loading flag to false to allow new requests to be made
        loading = false;
      } else {
        // If there are no more images to load, remove scroll event listener to prevent further requests
        window.removeEventListener(&quot;scroll&quot;, checkScroll);
      }
    }
  };

  // Send AJAX request with offset and limit parameters
  xhr.send(&quot;offset=&quot; + offset + &quot;&amp;limit=&quot; + limit);
}

// Function to check if user has scrolled to bottom of page
function checkScroll() {
  if (
    window.scrollY + window.innerHeight &gt;=
    document.documentElement.scrollHeight
  ) {
    // If user has scrolled to bottom of page and no requests are currently loading, call loadImages() function to fetch new images
    if (!loading) {
      loadImages();
    }
  }
}

// Attach scroll event listener to window object to trigger checkScroll() function when user scrolls
window.addEventListener(&quot;scroll&quot;, checkScroll);

// Load initial images
loadImages();

loadToApprovePrompts:

&lt;?php
include_once(&quot;bootstrap.php&quot;);

// Start output buffering
ob_start();

// Retrieve offset and limit values from POST request
$offset = $_POST[&#39;offset&#39;];
$limit = $_POST[&#39;limit&#39;];

// Retrieve array of images from database using the offset and limit values
$images = Prompt::getAllToApproveImages($offset, $limit);

// Encode the array of images as a JSON object and send it back as the response to the AJAX request
echo json_encode($images);

// Flush the output buffer
ob_end_flush();

答案1

得分: 1

为什么不添加一个链接标签而不是图像标签?

AJAX文件 infiniteScrollToApprove.js

var offset = 0;
var limit = 20;

// 初始化加载标志
var loading = false;

function loadImages() {
  // 将加载标志设置为true,以防止同时发出多个请求
  loading = true;

  // 创建新的XMLHttpRequest对象
  var xhr = new XMLHttpRequest();

  // 设置请求方法,URL和标头
  xhr.open("POST", "./loadPromptsToApprove.php", true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

  // 处理来自服务器的响应
  xhr.onload = function () {
    if (xhr.status === 200) {
      // 解析JSON响应
      var images = JSON.parse(xhr.responseText);
      console.log("已解析的图像:", images);

      // 循环遍历图像并创建图像元素
      if (images.length > 0) {
        for (var i = 0; i < images.length; i++) {
          var img = document.createElement("img");
          img.classList.add("flex", "w-1/4");
          img.setAttribute("src", images[i].cover_url);
          var aItem = document.createElement("a");
          aItem.setAttribute("href", "promptDetails.php?id=" + images[i].id);
          aItem.appendChild(img)
          document.getElementById("image-container").appendChild(aItem);
        }

        // 更新偏移量以跟踪加载的图像数量
        offset += limit;

        // 将加载标志设置为false,以允许进行新的请求
        loading = false;
      } else {
        // 如果没有更多图像可加载,删除滚动事件侦听器以防止进一步的请求
        window.removeEventListener("scroll", checkScroll);
      }
    }
  };

  // 使用偏移量和限制参数发送AJAX请求
  xhr.send("offset=" + offset + "&limit=" + limit);
}

// 用于检查用户是否滚动到页面底部的函数
function checkScroll() {
  if (
    window.scrollY + window.innerHeight >=
    document.documentElement.scrollHeight
  ) {
    // 如果用户滚动到页面底部并且当前没有加载请求,请调用loadImages()函数来获取新的图像
    if (!loading) {
      loadImages();
    }
  }
}

// 将滚动事件侦听器附加到窗口对象,以在用户滚动时触发checkScroll()函数
window.addEventListener("scroll", checkScroll);

// 加载初始图像
loadImages();

请注意,代码部分未进行翻译。

英文:

Why don't you append a link tag instead of the img tag?

AJAX file infiniteScrollToApprove.js

var offset = 0;
var limit = 20;
// Initialize loading flag
var loading = false;
function loadImages() {
// Set loading flag to true to prevent multiple requests from being made simultaneously
loading = true;
// Create new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set request method, URL and headers
xhr.open(&quot;POST&quot;, &quot;./loadPromptsToApprove.php&quot;, true);
xhr.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);
// Handle response from server
xhr.onload = function () {
if (xhr.status === 200) {
// Parse JSON response
var images = JSON.parse(xhr.responseText);
console.log(&quot;Parsed images:&quot;, images);
// Loop through images and create img elements
if (images.length &gt; 0) {
for (var i = 0; i &lt; images.length; i++) {
var img = document.createElement(&quot;img&quot;);
img.classList.add(&quot;flex&quot;, &quot;w-1/4&quot;);
img.setAttribute(&quot;src&quot;, images[i].cover_url);
var aItem = document.createElement(&quot;a&quot;);
aItem.setAttribute(&quot;href&quot;, &quot;promptDetails.php?id=&quot;+images[i].id);
aItem.appendChild(img)
document.getElementById(&quot;image-container&quot;).appendChild(aItem);
}
// Update offset to keep track of number of images loaded
offset += limit;
// Set loading flag to false to allow new requests to be made
loading = false;
} else {
// If there are no more images to load, remove scroll event listener to prevent further requests
window.removeEventListener(&quot;scroll&quot;, checkScroll);
}
}
};
// Send AJAX request with offset and limit parameters
xhr.send(&quot;offset=&quot; + offset + &quot;&amp;limit=&quot; + limit);
}
// Function to check if user has scrolled to bottom of page
function checkScroll() {
if (
window.scrollY + window.innerHeight &gt;=
document.documentElement.scrollHeight
) {
// If user has scrolled to bottom of page and no requests are currently loading, call loadImages() function to fetch new images
if (!loading) {
loadImages();
}
}
}
// Attach scroll event listener to window object to trigger checkScroll() function when user scrolls
window.addEventListener(&quot;scroll&quot;, checkScroll);
// Load initial images
loadImages();

huangapple
  • 本文由 发表于 2023年4月7日 02:20:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定