如何显示对视图的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 上测试这个

我建议你升级你的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配置。

//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;
});
}

我认为您在请求时没有设置 X-Request-With 标头。此问题是由于 CORS 造成的。尝试研究 CORS,在进行跨域请求时非常重要。

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

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

相关内容

最新更新