Ajax调用打印假后返回Ajax

2023-09-10 22:01:27 作者:勾嘴笑

能否请你帮我明白为什么这个返回false? Response.data返回true,我将其指定为变量有效,但是当我在最后返回它,那是假的。

Could you please help me to understand why this returns false? Response.data returns true, I assign it to variable 'valid' but when I return it at the end, it is false.

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;
        };

感谢你在前进。

推荐答案

该函数返回false,因为它是异步的,并且它未收到服务器的响应尚未从您的文章的要求。

The function returns false because it is asynchronous, and it hasnt received the server response yet from your post request.

如果你想使用函数返回值做一些事情一旦表单验证/服务器响应,那么你可以使用角度的$ Q

If you want to use functions return value to do something once the form has validated/server has responded, then you can use 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请求返回一个承诺对象)。

In case of your example, you can simply return the $http.post()'s return value, and use that instead ( $http requests return a promise object ).

//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);
});