angularjs是如何监听XMLHttpRequest事件的?

在线DEMO:

https://plnkr.co/edit/KAwhab7...

(function(angular) {
  'use strict';
angular.module('scopeExample', [])
  .controller('MyController', ['$scope','$timeout', function($scope,$timeout) {
   $scope.greeting='hhh'

   var httpRequest = new XMLHttpRequest();

    httpRequest.onreadystatechange = function(){ 
      console.log(httpRequest)
      if(httpRequest.readyState==2){ //不更新
        $scope.greeting='000'
      }
      // if(httpRequest.readyState==1){//更新 
      //   $scope.greeting='000'
      // }
    };

    httpRequest.onload = function(){
      // 不更新 
      // $scope.greeting='333'
    }
 
    httpRequest.open('GET', 'https://www.json-generator.com/api/json/get/bHEfYDDHEy?indent=2');

    httpRequest.send();

  }]);
})(window.angular);


为什么angularjs只有在readyState==1会更新数据?最好可以结合源代码解释

阅读 2.5k
1 个回答

因为你监听的是readyState本身就是会从0-4变化,你应该结合state是否为200进行数据更新判断

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题