在ajax调用之后返回打印false

时间:2015-03-11 22:38:46

标签: ajax angularjs

你能帮我理解为什么这会失败吗? Response.data返回true,我将其分配给变量' valid'但是当我最后归还它时,这是错误的。

var  valid = false;

factory.validate = function(id)
{

            data ={ 'id' : id };
            $http.post('php/validate.php', data).then
            (
                function(response)
                {
                    valid = response.data;
                    // Prints true here
                    console.log(response.data);
                    console.log(valid);
                },
                function(error)
                {
                    console.log(error);
                }
            );

            // Returns and prints false here
            console.log(valid);
            return valid;
        };

提前谢谢。

1 个答案:

答案 0 :(得分:0)

该函数返回false,因为它是异步的,并且它还没有从您的post请求收到服务器响应。

如果您希望在表单验证/服务器响应后使用函数返回值来执行某些操作,那么您可以使用angular' s $ q

this.validate = function() {
    var deferred = $q.defer(); 
    setTimeout(function() {//or do your post request that takes some time
        deferred.resolve();//validate the response etc and resolve as true.
        //or if something went wrong or didnt validate, reject.
        deferred.reject("Your form contained some errors"); 
    },1000);
    return deferred.promise;
}

如果是您的示例,您只需返回$ http.post()的返回值,然后使用它($ http请求返回一个promise对象)。

//your code with minor edits
factory.validate = function(id) {
    var deferred = $q.defer();
    var data ={ 'id' : id };
    $http.post('php/validate.php', data).success(function(response) {
        if ( response.is_valid ) {deferred.resolve("all OK");}
        else {deferred.reject("Error: your data is invalid");}
    }).error(function() {
        deferred.reject("Error:could not contact the server");
    });
    return deferred.promise;
};

//then use the validation code like this
validate(112).then(function() {
    //things validated and all is OK, give user some feedback
    alert("your stuff is valid");
},function(message) {
    alert(message);
});