如何在 Javascript 中的 $http 之前强制 $.getJSON 到 运行?

How do I force $.getJSON to run before $http in Javascript?

我的网页控制器中有以下 Javascript 代码。

 $.getJSON('resources/properties/properties.json', function(data) {
    $scope.properties = data; 
    });

$http({
    method: 'GET',
    url: $scope.properties.Properties.dataLocation
        }).
        success(function (data) {
        $scope.all_types_and_configs = data;
        $scope.exec = [];    
        }).
        error(function (data) {
        $scope.error = data.message;
        $scope.data = '';
        return;
        });
});

要获取的json文件的结构不是问题。

它应该先 运行 $.getJSON 命令然后运行 $http-request,因为$http 请求得到它的url 来自顶部 $.getJSON 部分中定义的变量,但是当我在它下面执行 console.log(properties) 时,它会吐出 "undefined"。

为什么代码没有按照编写的顺序执行?

它是异步执行的,所以两个调用都是独立完成的。 $.getJSON 有第三个参数——成功回调,这是同步它们的方式。 http://api.jquery.com/jquery.getjson/

不确定为什么要混合使用 jQuery AJAX 和 Angular $http?

您可以使用 JQuery.done,它将在您的请求完成后执行您的代码。

示例:

(function() {
  var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
  $.getJSON( flickerAPI, {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  })
    .done(function( data ) {
      $.each( data.items, function( i, item ) {
        $( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
        if ( i === 3 ) {
          return false;
        }
      });
    });
})();

与在收到 JSON 后,您已经获得 $scope.properties = data; 到 运行 行的方式相同。你把它放在传递给 getJSON.

的回调函数中

Why is the code not executing in the order that it is written?

是。

getJSON(url, foo) 表示 "Make an HTTP request to the url and set up an event handler to call foo when the response is received".

您似乎希望它等待 响应,然后再做任何事情。那会锁住 UI 并且很可怕。

代码按照写的顺序执行,只有回调函数在相应的请求完成时执行。所以你应该把第二个调用放在第一个回调中:

$.getJSON('resources/properties/properties.json', function(data) {
    $scope.properties = data;
    $http({method: 'GET', url: $scope.properties.Properties.dataLocation}).
        success(function (data) {
            $scope.all_types_and_configs = data;
            $scope.exec = [];    
        }).
        error(function (data) {
           $scope.error = data.message;
           $scope.data = '';
           return;
        });
    });
});