[英]Jquery AJAX calls in a loop
In my app, a displays available timeslots (for appointment). 在我的应用程序中,显示可用的时隙(用于约会)。 I want to add a class 'taken' to the slots () which are already taken.
我想将一个“ taken”类添加到已经使用的slot()中。 For this I wrote the following code.
为此,我编写了以下代码。
$("td").each(function(){
var send = $(this).text();
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get',
success: function(result){
console.log(result);
if (result.status === "taken") {
$(this).addClass('taken');
};
}
});
});
It's supposed to perform an ajax call, and if the result for a slot is 'taken', add the class 'taken' to corresponding . 它应该执行ajax调用,并且如果slot的结果是“ taken”,则将class“ taken”添加到相应的。 It does the ajax call part, but adds the class to all td elements in the table, not just the taken ones.
它执行ajax调用部分,但将类添加到表中的所有td元素上,而不仅是采用的元素上。
the check-availability.php, returns 'taken' when called it in browser but nothing happens. 在浏览器中调用check-availability.php时,它返回“ taken”,但没有任何反应。 Also, when the condition is changed into result.status === "notTaken" , all the s are added the class 'taken'
另外,当条件更改为result.status ===“ notTaken”时 ,所有s都添加为“ taken”类
How do I fix this? 我该如何解决?
$("td").each(function(){
var that = this;
var send = $(this).text();
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get',
success: function(result){
console.log(result);
if (result.status === "taken") {
$(that).addClass('taken');
};
}
});
});
see this for more reference: $(this) inside of AJAX success not working 请参阅此以获得更多参考: AJAX成功内的$(this)无法正常工作
instead of success, try using .done()
而不是成功,请尝试使用
.done()
example 例
`
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get'
}).done(function(result) {
console.log(result);
if (result.status === "taken") {
$(this).addClass('taken');
};
});
`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.