0

Hello all i am having a problem with my Jquery function. i have a variable called "var checkBit" I perform a $ajax action and based on that i set the "checkBit" to either 1 or 0. But when i alert the "checkBit" it always shows 0 even when i have reassigned it the value 1. I have commented on the code where i have the problem. Here is my code:

function checkStatusType(statusId){
    var checkBit = 0; //deceleration of variable and initially assigned 0
    $.ajax({ //ajax action performed
        url:'ajax_1.php',
        type:'GET',
        data:{task:'check_status_type',id:statusId},
        dataType: 'json',
        cache:false,
        success:function(data){
            if(data.length > 0){

                if(data != 0){ //here i am checking if the value of "data" //is 1 or not
                    $('#expected-return-time').slideDown();
                    checkBit = 1;  //based on the above check i assign 
                    //either 1 or 0 to the variable

                    //alert(checkBit); when i alert it here it works fine
                } else {

                    $('#expected-return-time').remove();
                    checkBit = 0;  // same here 
                    //alert(checkBit);

                }
            } else {
                alert('Sorry unable to find the status ID');
            }


        },error: function(data) {
            console.log('Error: ' + data);
        }

    });
    alert(checkBit); //problem when i alert the variable here it always 
    //shows 0 only every time. I dont know whats wrong with it.

}

My basic objective was that my function will return the variable and based on value 1 or 0 i have different functions that i perform. if there more effective way of doing i did like to learn. Thank you very much.

4

2 回答 2

0

Ajax 查询是异步的,它不等待完成并执行alert(checkBit);

像这样使用 smt:

$.ajax({ //ajax action performed
url:'ajax_1.php',
type:'GET',
data:{task:'check_status_type',id:statusId},
dataType: 'json',
cache:false,
success:function(data){
      finish();
}});

function finish() {
    alert(checkBit);
}
于 2013-06-11T06:44:23.303 回答
0

最后调用的问题:

alert(checkBit);

这是在 ajax 的响应完成之前发生的,因此每次都会显示 0。我建议将回调函数传递给 checkStatusType 以封装您希望对返回的校验位进行的处理。

于 2013-06-11T06:44:44.023 回答