我正在使用窗口滚动上的Ajax从数据库中获取数据。每当我滚动窗口时,它都会调用ajax并一次又一次地加载数据。 例如,数据库中有5行,我在每个调用中都提取2行,因此在提取5行之后它应该停止提取行,但它会不断提取行并进行复制。因此,当获取5行数据时,我需要如何停止此调用的帮助。
jQuery代码
$(document).ready(function(){
var _token = $('input[name="_token"]').val();
load_data('', _token);
function load_data(id="", _token) {
$.ajax({
url:"{{ route('loadmore.load_data') }}",
method:"POST",
data:{
id:id,
_token:_token
},
success:function(data) {
$('#load_more_button').remove();
$('#post_data').append(data);
}
});
}
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
// ajax call get data from server and append to the div
var id = $(this).data('id');
$('#load_more_button').html('<b>Loading...</b>');
load_data(id, _token);
}
});
});
控制器
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class LoadMoreController extends Controller
{
function index()
{
return view('load_more');
}
function load_data(Request $request)
{
if($request->ajax()) {
if($request->id > 0) {
$data = DB::table('ajaxpracticetable')
->where('id', '<', $request->id)
->orderBy('id', 'DESC')
->limit(3)
->get();
} else {
$data = DB::table('ajaxpracticetable')
->orderBy('id', 'DESC')
->limit(3)
->get();
}
$output = '';
$last_id = '';
if(!$data->isEmpty()) {
foreach($data as $row) {
$output .= '
<div class="row">
<div class="col-md-12">
<h3 class="text-info"><b>'.$row->first_name.'</b></h3>
<p>'.$row->last_name.'</p>
<br />
<div class="col-md-6">
<p><b>Published</b></p>
</div>
<div class="col-md-6" align="right">
<p><b><i>By - abdullah</i></b></p>
</div>
<br />
<hr />
</div>
</div>
';
$last_id = $row->id;
}
} else {
// here I want to write code that will restrict that data to fetch repeatedly
}
echo $output;
}
}
}
答案 0 :(得分:0)
您可以使用js变量存储请求计数。
var cnt = 0;
var xhr;
$(document).ready(function(){
var _token = $('input[name="_token"]').val();
load_data('', _token);
function load_data(id="", _token) {
if(cnt >= 5) {
xhr.abort();
$(window).unbind('scroll');
return false;
}
xhr = $.ajax({
url:"{{ route('loadmore.load_data') }}",
method:"POST",
data:{
id:id,
_token:_token
},
success:function(data) {
cnt += 1;
$('#load_more_button').remove();
$('#post_data').append(data);
}
});
}
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
// ajax call get data from server and append to the div
var id = $(this).data('id');
$('#load_more_button').html('<b>Loading...</b>');
load_data(id, _token);
}
});
});