javascript - 为什么我的 ajax 请求重复来自 Laravel Controller 的相同数据?

标签 javascript ajax laravel

目标:当用户单击“加载更多”按钮时,使用 ajax 请求将更多行从数据库加载到 View 中。我希望在不重新加载页面的情况下加载数据。

问题:通过 ajax 加载的数据在每个请求中不断重复相同的行,并且不按照标准请求进行分页。

详细信息: 我有一个从数据库加载 4 行的 View ,我使用 Laravel 的内置分页功能对其进行分页。我在“加载更多”按钮上添加了一个事件监听器,该按钮成功将请求发送到 Controller ,而 Controller 又成功返回数据。 Controller 返回我想要显示的数据的部分 View 。然而,这些数据似乎没有正确增加,并且不断重复每个请求上显示的记录。我不确定我在这里缺少什么,问题是在 controller 中还是在 JS 中?

我对 LaravelPHPJS 不太有经验,因为我更多地来自于网页设计师和 UI 设计背景,很想真正了解我在这里做错了什么。

请不要提供 JQUERY 示例。

部分 View :

@foreach ($products as $product)
    <div style="background-color:pink; width: 200px;">
        <p>{{ $product->title }}</p>
        <img src="/images/product/{{ $product->img }}" alt="{{ $product->title }}" style="width: 50px;">
    </div>
@endforeach

Javascript: (我正在更新按钮 href 属性,以便请求 URL 反射(reflect)正确的查询)

const container = document.querySelector('#sandbox-container');
let button = document.getElementById('load-stuff');
let url = button.getAttribute('href'); // http://127.0.0.1:8000/sandbox?page=2
let pageNum = button.getAttribute('href').substr(35,1);

button.addEventListener('click', (event) => {
    event.preventDefault();
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    // if page loads successfully, replace the number at the end of the url with the incremented page number
    pageNum++;
    newUrl = url.replace(/page=([^d]*)/, `page=${pageNum}`);
    button.setAttribute('href', newUrl);

    xhr.onload = function() {
        if (xhr.status === 200) {  
            container.insertAdjacentHTML('beforeend', xhr.responseText);
        }
        else {
            console.log(`Request failed, this is the response: ${xhr.responseText}`);
        }
    };     
    xhr.send();     
})

Controller :

public function sandbox(Request $request)
    {      
        $products = Product::orderBy('title', 'asc')->paginate(4);

        if($request->expectsJson()){
            return view('sandbox-more', compact('products'));
        } else {
            return view('sandbox', compact('products'));
        }  
    }

最佳答案

考虑将此代码片段用于您的 JavaScript

const container = document.querySelector('#sandbox-container');
let button = document.getElementById('load-stuff');

button.addEventListener('click', (event) => {
    event.preventDefault();
    const xhr = new XMLHttpRequest();

    let url = button.getAttribute('href');
    let pageNum = button.getAttribute('data-page-number') || 0;

    xhr.open('GET', url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    // if page loads successfully, replace the number at the end of the url with the incremented page number
    pageNum++;
    newUrl = url + '?page=' + pageNum;

    xhr.onload = function() {
        if (xhr.status === 200) {  
            container.insertAdjacentHTML('beforeend', xhr.responseText);
            button.setAttribute('data-page-number', pageNum);
        }
        else {
            console.log(`Request failed, this is the response: ${xhr.responseText}`);
        }
    };     
    xhr.send();     
})

我在这里所做的是将页码保存到专用的自定义属性“数据页码”中。执行“button.getAttribute('href').substr(35,1)”效率很低。然后检查页码并在按钮的单击事件上递增它。此外,仅在请求成功时更新“data-page-number”属性。我希望这有帮助

关于javascript - 为什么我的 ajax 请求重复来自 Laravel Controller 的相同数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58183297/

相关文章:

javascript - 我的 Ajax PHP 代码无法正常工作

php - Laravel 以编程方式获取特定页面

php - Laravel 8 强制更改密码

php - 在laravel现在日期时间显示错误

javascript - 防止 href ="#"链接更改 URL 哈希

javascript - Bootstrap Datetimepicker 剩余秒数

javascript - 替换响应表以获得更好的标记和可访问性

javascript - 在 Django 模板中动态生成动态表单

php - 使用ajax成功提交表单后重新加载页面

javascript - 如何在文档准备好时使 Jquery 可折叠面板折叠而不是展开?