如何向视图显示JSON响应,我做错了什么?

时间:2017-07-17 02:45:03

标签: javascript angularjs json

我昨天刚刚开始学习AngularJS并构建一个练习应用程序来显示用户在搜索栏中输入的图像。

到目前为止我的代码

HTML

<body>

  <div id="content" ng-app="FlickerApp" ng-controller="MainController">

        <h3>Search images in real time!</h3>

          <input type="text" ng-model="searchPic" />
          <button class="btn btn-primary" ng-click="showPics()">Search</button>

        <div id="flickerPics" >
          <ul ng-repeat="ph in data.photo">
            <li>
              {{ ph.id }}
              {{ response }}
              <img src="https://farm{{ ph.farm }}.staticflickr.com/{{ ph.server}}/{{ ph.id}}_{{ph.secret}}.jpg" 
              style="width:304px;height:228px;">
            </li>
          </ul>
        </div>

      </div>

JavaScript

    angular.module("FlickerApp",[]).controller("MainController",                         
    function($scope, $http){

    $scope.showPics = function () {

    $http.get("https://api.flickr.com/services/rest/?   method=flickr.photos.search&api_key=[API_KEY_HERE]&tags="  +$scope.searchPic+  "&in_gallery=1&is_getty=1&per_page=5&format=json&nojsoncallback=1")
.success(function(data){
  $scope.data = data.photos;
}).error(function(data, status){
    $scope.response = data + status;
    });
    }

    });

我没有输入API密钥,因为我手动测试了网址。

我正在JSFiddle上测试这个

3 个答案:

答案 0 :(得分:0)

//try this
 $http.get("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[API_KEY_HERE]&tags="  +$scope.searchPic+  "&in_gallery=1&is_getty=1&per_page=5&format=json&nojsoncallback=1") 
 .then(function(result){
    $scope.data = result.data;
  }).error(function(data, status){
    $scope.response = data + status;
  });
}

答案 1 :(得分:0)

我建议你升级你的AngularJS版本。似乎您正在使用其中一个设置X-Requested-With请求标头的旧标头,该标头与大多数CORS配置不兼容。

然而,有一种解决方法。试试这个

$http.get('https://api.flickr.com/services/rest/', {
  params: {
    method: 'flickr.photos.search',
    api_key: [API_KEY_HERE],
    tags: $scope.searchPic,
    in_gallery: 1,
    is_getty: 1,
    per_page: 5,
    format: 'json',
    nojsoncallback: 1
  },
  headers: {
    'X-Requested-With': null
  }
}).then(function(response) {
  $scope.data = response.data.photos;
})

即使您升级,我强烈建议您保留上面的params配置。您不需要header配置。

答案 2 :(得分:-1)

我认为你在请求时没有设置X-Requested-With标头。此问题归因于CORS。尝试研究CORS,在进行跨域请求时非常重要。

尝试在请求中添加标题,如下所示:

$http({
'url':'yourUrl',
'method':'get',
'headers': { 'X-Requested-With' :'XMLHttpRequest'}
});