【问题标题】:Laravel ajax pagination loads entire pageLaravel ajax 分页加载整个页面
【发布时间】:2019-10-01 18:33:41
【问题描述】:

我正在尝试使用“加载更多”按钮而不是 Laravel 的默认分页来创建 ajax 分页。现在,过去几天我一直在网上搜索解决方案,但一切都是 jquery,而且我对 javascript 和 Laravel 还比较陌生。我宁愿避免使用 jquery,因为我试图更好地使用 vanilla javascript。

我已经尝试了这个网站上我能找到的所有建议,但没有一个适合我。

索引视图对 4 个项目进行分页(此时出于测试目的),并且在每个 ajax 请求中,我想呈现接下来的 4 行。

我的问题是,ajax 请求会呈现整个页面,而不仅仅是来自数据库的数据。我的代码做错了什么?

控制器:

public function sandbox(Request $request)
    {

        $response = array(
            'status' => 'success',
            'msg' => $request->message,
        );

        $products = Product::orderBy('title', 'asc')->paginate(4);

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

Javascript:

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

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

    xhr.onload = function() {
        if (xhr.status === 200) {  
            container.insertAdjacentHTML('beforeend', xhr.responseText); // ouputs entire view instead of the partial
            console.log(xhr.responseText);
        }
        else {
            console.log(`Request failed, this is the response: ${xhr.responseText}`);
        }
    };

    xhr.send();     
})

要在 ajax 请求上加载的部分视图

@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

我不确定我需要做什么才能将 xhr.responseText 呈现为仅 $products 数据?我尝试将其作为 json 数据发送,但每次都返回 null。我希望有人可以在这里帮助一个菜鸟,在此先感谢!

【问题讨论】:

  • 如果你使用return view($x),你将返回一个 Laravel 呈现给 HTML 的视图响应。如果你使用return view($x)-&gt;render(),你将返回已经渲染的 HTML(即你做 Laravel 的工作)。你想要的是用return response()-&gt;json(['some' =&gt; 'data']) 返回json。如果你需要分页,你应该使用API resources,它确实改进了这部分。

标签: javascript ajax laravel


【解决方案1】:

我设法使用xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');修复它

【讨论】:

    猜你喜欢
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多