【问题标题】:jquery correct syncronous ajax calljquery正确的同步ajax调用
【发布时间】:2016-01-10 00:20:49
【问题描述】:

我需要在函数内部调用 jquery ajax 函数并检查响应数据

function checkInput(){
    var success;
    $.ajax({...}).then(function (data) {
        success = data.response
        console.log(success); // true/false correct!
        if (success)
            call_other_func(); // works
    });
    console.log(success); // undefined;

    return success; // i need to return success variable        
}

其他函数调用checkInput

if (checkInput()){
        console.log('correct input value'); 
    }
else{
     call_error_validation_func();
}

使用 async:false 可以,但方法不正确。

我该怎么办?

谢谢

【问题讨论】:

    标签: jquery ajax asynchronous .when


    【解决方案1】:

    您的问题是理解 javascript 中的异步调用。 您可能应该做的是返回一个委托,然后在 ajax 调用完成时获取返回的值。

    这是一个例子:

    function checkInput(){
        var success;
        var delegate = $.ajax({...});   
    
        return delegate;
    }
    
    var delegate = checkInput();
    
    delegate.done(function(data){
        console.log(data); //will show you'r results
    
        // Do whatever you need here
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多