目标:当用户单击“加载更多”按钮时,使用 ajax
请求将更多行从数据库加载到 View 中。我希望在不重新加载页面的情况下加载数据。
问题:通过 ajax
加载的数据在每个请求中不断重复相同的行,并且不按照标准请求进行分页。
详细信息: 我有一个从数据库加载 4 行的 View ,我使用 Laravel 的内置分页功能对其进行分页。我在“加载更多”按钮上添加了一个事件监听器,该按钮成功将请求发送到 Controller ,而 Controller 又成功返回数据。 Controller
返回我想要显示的数据的部分 View 。然而,这些数据似乎没有正确增加,并且不断重复每个请求上显示的记录。我不确定我在这里缺少什么,问题是在 controller
中还是在 JS
中?
我对 Laravel
、PHP
和 JS
不太有经验,因为我更多地来自于网页设计师和 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/