如果成功执行Jquery ajax函数,则调用另一个jquery函数

时间:2011-11-13 18:53:18

标签: jquery

执行Jquery ajax函数时,如果成功则调用其他jquery函数,该函数将值返回给第一个函数

// JavaScript文档

    button = function(first,last) {
    var butVal21  = $('#button21').val();   
    var butVal22  = $('#button22').val();   


    doPost('cross.php',
                    'first=' + first +
                    '&button22=' + butVal22 +
            '&last=' + last,
                   function(response) {

                       if(buttonVal == '') {
                                            $('#button'+first+last).val("X");
                        var status = checkSucess(first,last,'X');
    // I want to status value as return value for checkSucess function.
                        if (status != null) { return false; }

                        console.info(response);

                        }
                    }
        );

    }

    checkSucess = function(first,last,value) {
    doPost('sucess.php',
                    'first=' + first ,

                     function(response) {
                       if(response == 'X') {

                        return 'sucess';
                        }
                       else if(response == 'O') {

                        return 'failure';
                        }

                    }
        );
    }




    }

我想将状态值作为checkSucess函数的返回值。但是不能这样做。
其次我想在以下情况下停止一个jquery函数:if(status!= null),是否可以通过返回false

2 个答案:

答案 0 :(得分:1)

您实际上并没有从Ajax函数返回这样的值:Ajax调用将在未来的任意时间发生,在您对checkSuccess()进行调用后返回(相对)很久。

通常jQuery's .when() function可用于将多个Ajax调用链接在一起。

请参阅this fiddle作为链接Ajax函数的示例。第一个Ajax调用的结果将传递给进行第二次调用的函数。

答案 1 :(得分:0)

在我看来,一种可能的解决方案是将doPost调用从异步请求更改为同步请求,如下所示:

checkSucess = function(first,last,value) {
    var returnValue = 'failure';

    $.ajax({

        async: false, 

        url:'sucess.php',
        data:'first=' + first ,

        success: function(response) {
                       if(response == 'X') {

                        returnValue = 'sucess';
                        }
                       else if(response == 'O') {

                        returnValue = 'failure';
                        }

                    }
        });
        alert(returnValue);
        return returnValue;
    }