如何在angularjs中调用sync和async?

时间:2015-01-21 11:39:23

标签: javascript angularjs angularjs-scope

我想在下面的angularjs中进行自定义同步和异步。

  var async = function (url, data, action, callback) {   
        $.ajax({
            url: global.baseURL + url,
            type: action,
            data: data,                
            async: true,//or false
            success: function (data) {
                if (data !== undefined && data !== null) {
                    callback(data);
                }
            }
        });
    }; 

在AngularJs中看起来像这段代码

 $http({ method: 'GET', url: baseURL + 'Api/MobilePref/Get/'+uid
        })
        .success(function (data, status, headers, config) {
        })
        .error(function (data, status, headers, config) {
            //TODO: handl error.
        });

任何人都可以告诉我如何在angularjs中设置同步和异步调用吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

function callAjax(url, callback){
    var xmlhttp;

    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, true); // the flag true tell if this is async or not and then you can call $scope.$apply for angular to know.
    xmlhttp.send();
}