如何使用 AngularJS 执行 XMLHttpRequest (AJAX)

How to do XMLHttpRequest (AJAX) with AngularJS

我正在尝试在 POST 请求中使用 AngularJS,但我无法在活动中使用 $scope

那是我的代码(出于演示目的,我只是在 Angular 构造中添加状态):

myApp.controller('myController', function myController($scope) {
    $scope.myVal = [{status:"before (working)"}];

    doRequest(p1, p2, myCallback.bind(null, $scope));

    function myCallback($scope, a) {
        $scope.myVal = [{ status: a }];
    }

    function doRequest(p1, p2, callback) {
        $scope.myVal = [{ status: "prepare request (working)" }];

        var xhr = new XMLHttpRequest();
        var url = "http://...";
        xhr.open("POST", url, true);
        //....
        xhr.send(myQuery);

        $scope.myVal = [{ status: "after post send (working)" }];
        callback("after post via callback (working)");

        //callback working till this point

        xhr.onreadystatechange = function () {

            if (xhr.readyState === 4 && xhr.status === 200) {
                callback("in event (NOT working)"); 
                //This is NOT working anymore (even this point is reached)!
            }
        };
    }

通过代码中的注释添加,回调一直有效,直到 EventHandler 分配。

我正在寻找的是:如何使用回调(或更准确地说,如何在事件处理函数中制作 $scope available/transfered)?

您不需要将 $scope 传递到 callback,因为 $scope 是在控制器范围内定义的。

你在使用"native" Ajax时可能会遇到问题,因为这个操作在Angular之外,angular不知道,你需要让它熟悉 Angular 和 $scope.$apply.

如果您需要创建快捷方式,Angular 使用 $http 服务为您完成。

您可以将整个 XMLHttpRequest 替换为注入 $http 并调用 .post 方法:

myApp.controller('myController', function myController($scope, $http) {
    $scope.myVal = [{status:"before (working)"}];

    doRequest(p1, p2);

    function doRequest(p1, p2) {
        $scope.myVal = [{ status: "prepare request (working)" }];
        $http.post(url, myQuery).then(() => {
           $scope.myVal = [{ status: 'Finished' }]; // $scope is available here
        });
    }
}