【问题标题】:How to do XMLHttpRequest (AJAX) with AngularJS如何用 AngularJS 做 XMLHttpRequest (AJAX)
【发布时间】:2017-12-03 04:18:25
【问题描述】:

我正在尝试在 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)!
            }
        };
    }

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

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

【问题讨论】:

  • 使用$http 发出请求。您正在尝试在角度上下文之外的异步代码中修改范围。当您这样做时,需要告诉 angular 运行摘要以更新视图。使用 $http 在内部处理这个问题
  • 欲了解更多信息,请参阅AngularJS $http Service API Reference

标签: javascript angularjs angularjs-scope angularjs-http


【解决方案1】:

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

你在使用“native”Ajax 时可能会遇到问题,因为这个操作在Angular 之外并且 angular 不知道,你需要通过$scope.$apply 使其熟悉 Angular。

如果您需要创建快捷方式,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
        });
    }
}

【讨论】:

    猜你喜欢
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2013-08-04
    • 2015-09-19
    • 2011-11-26
    • 2012-02-10
    相关资源
    最近更新 更多