Javascript 在角函数中调用AJAX

Javascript 在角函数中调用AJAX,javascript,ajax,angularjs,http,Javascript,Ajax,Angularjs,Http,在这段代码中,我对函数中的$http有两个问题 $scope.buttonClick = function(){ // Send input data $.post('lib/add_contact.php', $scope.contact, function(data){ data = angular.fromJson(data); if(!data.error){ $scope.conta

在这段代码中,我对函数中的$http有两个问题

$scope.buttonClick = function(){
    // Send input data
        $.post('lib/add_contact.php', $scope.contact, function(data){
            data = angular.fromJson(data);
            if(!data.error){
                $scope.contact = "";
                console.log('success');
            }else{
                console.log('error');
            }
        });

    // Next Code
    console.log('Next Code');
}
第一个问题是,当我想清除一个联系人时,它不会立即工作,而是在我按下输入键后才工作。 如果我把

在POST之外,它工作得很好

第二个问题是,为什么POST被称为last?代码的输出是

Code Next
success
但我希望输出是

success
Code Next

感谢您的想法和答案。

您正在使用jQuery进行ajax调用,这是在angular世界之外发生的。您需要触发范围更新的摘要周期,以便将更改反映在视图中

要解决此问题,请执行以下操作:

$scope.buttonClick = function(){
    // Send input data
        $.post('lib/add_contact.php', $scope.contact, function(data){
            data = angular.fromJson(data);
            if(!data.error){
                $scope.$apply(function(){ //<-- calling $apply()
                    $scope.contact = "";
                });
                console.log('success');
            }else{
                console.log('error');
            }
        });

    // Next Code
    console.log('Next Code');
}

AJAX是异步的,所以它被称为first,继续在后台运行,然后是console.log,稍后AJAX调用完成。谢谢,第一个解决方案工作得很好。我尝试使用$http,但在PHP中获取数据时遇到问题,所以我使用jQuery解决方案。
$scope.buttonClick = function(){
    // Send input data
        $.post('lib/add_contact.php', $scope.contact, function(data){
            data = angular.fromJson(data);
            if(!data.error){
                $scope.$apply(function(){ //<-- calling $apply()
                    $scope.contact = "";
                });
                console.log('success');
            }else{
                console.log('error');
            }
        });

    // Next Code
    console.log('Next Code');
}
$scope.buttonClick = function() {
    $http.post('lib/add_contact.php', $scope.contact).success(function(data) {
        data = angular.fromJson(data);
        if (!data.error) {
            $scope.$apply(function() { //<-- calling $apply()
                $scope.contact = "";
            });
            console.log('success');
        } else {
            console.log('error');
        }
    });
}