weixin_33743248 2015-02-26 05:42 采纳率: 0%
浏览 26

jQuery AJAX循环调用

In my app, a displays available timeslots (for appointment). I want to add a class 'taken' to the slots () which are already taken. 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 . It does the ajax call part, but adds the class to all td elements in the table, not just the taken ones.

the check-availability.php, returns 'taken' when called it in browser but nothing happens. Also, when the condition is changed into result.status === "notTaken", all the s are added the class 'taken'

How do I fix this?

  • 写回答

2条回答 默认 最新

  • weixin_33712987 2015-02-26 05:47
    关注
    $("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 jquery success scope

    评论

报告相同问题?