我已经学习Ajax一周了,我试图弄清楚我希望如何完成Ajax功能。
在jquery的函数中,我获得了索引中具有的几个按钮的ID,该ID由Ajax发送到名为“ task-category.php'”的外部文件,它唯一要做的就是一个sql查询到我的数据库,它以JSON的形式返回其答案,当我收到JSON时,我会对其进行遍历,并同时使用索引中的ajax进行打印。
当我想知道何时在索引屏幕上完成将所有json ajax打印以显示“搜索已成功执行”或“未找到数据”时,就会出现我的问题。
$(document).ready(function() {
$('ul#categoria li').click(function() {
let categoria = $(this).attr('id');
$.ajax({
url: 'task-categoria.php',
data: {categoria},
type: 'POST',
success: function (response) {
if(!response.error) {
let tasks = JSON.parse(response);
let template = '';
tasks.forEach(task => {
template += `<a href='index.php?idrec=${task.idrec}'>
<div class="img-container grid-item">
<img class="img-thumbnail" src="${task.imag}">
<div class="overlay">
<span>${task.tit}</span>
</div>
</div>
</a>`
});
$('#grid-container').html(template);
}
}
})
});
});
答案 0 :(得分:0)
答案 1 :(得分:0)
使您的api响应良好,如果您可以根据api响应添加条件,则可以轻松进行处理。您的api响应应如下所示
{'status': true, 'error': false, 'data': ['your data'], 'message':"Data Fetch successfully"}
我做了一些如下更改:- $(document).ready(function(){
$('ul#categoria li').click(function() {
let categoria = $(this).attr('id');
$.ajax({
url: 'task-categoria.php',
data: {categoria},
type: 'POST',
dataType: 'json',
success: function (response) {
// Best thing to do is that always use status of response true/false
if(!response.error) {
if(response.status == true) {
let tasks = JSON.parse(response);
let template = '';
tasks.forEach(task => {
template += `<a href='index.php?idrec=${task.idrec}'>
<div class="img-container grid-item">
<img class="img-thumbnail" src="${task.imag}">
<div class="overlay">
<span>${task.tit}</span>
</div>
</div>
</a>`
});
$('#grid-container').html(template);
}
alert('data fetch successfully');
} else {
alert('No data found');
}
},error: function (error) {
console.log('Some error occured please try later!');
}
})
});
});