1

我正在使用 angularJS 和 SLIM PHP restful 服务器,PHP 服务正在运行,实际上我已经使用 $http.get() 在这个应用程序中没有任何问题......但是现在发生了一件奇怪的事情,我创建了一个新函数与其他人一样,它得到 .success(function(data)) 没有问题,我实际上可以 console.log(data) 并显示正确的结果,但是当 .success() 完成并返回时,我收到未定义的结果。ps:浏览器控制台没有错误。

    var markerOptions = [];
    loadMarkers();
    console.log(markerOptions);

    function loadMarkers() {
    $http.get('http://localhost/rest/getMarkers').success(function(response){
            console.log(response);
            markerOptions = response;
    });
}
  • success() 中的 Console.log() 返回正确的数据
  • loadMarkers() 后的 Console.log() 返回 undefined
4

1 回答 1

4

@MarcKline's comments are correct. Anyways, following what I think you're trying to achive by this piece of code of yours, you can assign the returned data from the ajax response to a scope variable (assuming you're using $scope), e.g $scope.markerOptions = response. You can declare markOptions as a scope variable by var $scope.markOptions = [] (...and, of course, log it by console.log($scope.markOptions) accordingly). Also, define $scope.loadMarkers = function() {...} and call it by $scope.loadMarkers()

The scope will be updated as soon as the client-side gets its ajax response. Hope it helps your current needs in addition to a better understanding of javasciprt's async approach that some of its principles were explained to you by the comments.

于 2014-05-10T00:16:55.020 回答