我想从具有大量数据的服务器获取结果。 因此,服务器以多个页面发送数据。 所以我想让所有这些在数据表中显示它们。 所以我在循环中使用 Ajax 请求,因为我想从许多页面获取。 我为 page 变量添加 +1,因此循环将从所有页面获取所有结果,直到响应的元素数为 0。 但问题是浏览器在执行此请求时挂起?还有其他方法可以实现这一点吗?谢谢。
我尝试先获取数据,然后在循环后将它们添加到表中,但浏览器仍然相同。
$('#corporateComboOfAllCorpTag').change(function () {
let response=1;
let page=0;
$('#tableOfAllCorpTag').DataTable().destroy();
let corpParkStationTable=$('#tableOfAllCorpTag').DataTable({order:[]});
corpParkStationTable.clear();
let corpStations=[];
while (response!=0){
$.ajax({
url:corporateTagUrl+corporates[$('#corporateComboOfAllCorpTag').prop('selectedIndex')].corporateId,
method:"GET",
data:{
"size":1000,
"page":page
},
dataType:"json",
headers: { 'smart-session-key': sessionKey, 'userName': admin},
async:true,
success:function (resp) {
for (let i = 0; i < resp.content.length; i++) {
corpParkStationTable.row.add($(
'<tr><td>'+resp.content[i].tagSerial+'</td><td>'+resp.content[i].tagUid+'</td><td>'+resp.content[i].status+'</td><td>'+resp.content[i].addedBy+'</td><td>'+resp.content[i].addedDate+'</td><td><button class="btn btn-info">More</button></td></tr>'
)).draw(false);
corpStations.push(resp.content[i]);
}
response=resp.numberOfElements;
},
error:function (resp) {
console.log("Fail "+resp);
}
});
page++;
}
});
如果您设置async: false
那么它将起作用,但某些浏览器会抛出警告。
我认为您必须以同步方式编写代码。例如
function getDataFromAjax(){
$('#corporateComboOfAllCorpTag').change(function () {
$('#tableOfAllCorpTag').DataTable().destroy();
let corpParkStationTable=$('#tableOfAllCorpTag').DataTable({order:[]});
corpParkStationTable.clear();
let corpStations=[];
function getPagewiseData(pageNum){
$.ajax({
url:corporateTagUrl + corporates[$('#corporateComboOfAllCorpTag').prop('selectedIndex')].corporateId,
method:"GET",
data:{
size:1000,
page:pageNum
},
dataType:"json",
headers: { 'smart-session-key': sessionKey, 'userName': admin},
async:true,
success:function (resp) {
for (let i = 0; i < resp.content.length; i++) {
corpParkStationTable.row.add($(
'<tr><td>'+resp.content[i].tagSerial+'</td><td>'+resp.content[i].tagUid+'</td><td>'+resp.content[i].status+'</td><td>'+resp.content[i].addedBy+'</td><td>'+resp.content[i].addedDate+'</td><td><button class="btn btn-info">More</button></td></tr>'
)).draw(false);
corpStations.push(resp.content[i]);
}
response=resp.numberOfElements;
if(resp.numberOfElements>0){
getPagewiseData(pageNum+1)
}
},
error:function (resp) {
console.log("Fail "+resp);
}
});
}
getPageWiseData(0);
}
getDataFromAjax();