如何首先获得AJAX结果,然后才运行下一个函数

时间:2014-06-05 19:43:18

标签: javascript ajax stapes.js

好的,情况就是这样,我正在验证form。此表单有4个输入框。在此表单上完成了2次验证。一次验证检查3个框是否有某些值(使用parsely执行此操作)。一个框有一些代码,我必须将此代码发送到服务器以运行检查代码是否有效。以下是我如何做到这一点:

(伪代码)

onFormSubmit(){
    var isValid,

    //This is a callback and to get the result of ajax. Ajax function is in different file
    validateCode = function(response){
         isValid = response; // true or false
    };

   isValid = $('#form').parsley('validate');

    //Calling that other file function for ajax result, arguments are passed as object validateCode is function name.
   this.emit('validateCode', {value:promoCodeValue, validate:validateCode});


   // Here in this function, the value of isValid is not updating properly. It is taking the value given by parsley validation.
   doOtherStuff(isValid)

}

所以我的问题是,有没有办法帮助我等待ajax完成然后运行doOtherStuff函数。

1 个答案:

答案 0 :(得分:0)

您只需重新安排一下代码。

onFormSubmit(){
    var isValid;
     //This is a callback and to get the result of ajax. Ajax function is in different file
     validateCode = function(response){
         isValid = response && $('#form').parsley('validate'); // true or false
         //Calling that other file function for ajax result, arguments are passed as object validateCode is function name.
         this.emit('validateCode', {value:promoCodeValue, validate:validateCode});
         // Here in this function, the value of isValid is not updating properly. It is taking the value given by parsley validation.
         if(isValid){
              doOtherStuff(isValid);
         }
     };
}