所以我能够向yelp API提出第一个JSONP请求,以便为我返回业务数据,但是我所做的任何后续请求都会导致失败的回调,记录状态代码为404.但是当我拉起来时Chrome开发工具中的网络选项卡我看到我发出的所有后续GET请求都具有状态200,我确实看到了有效的响应数据。当调用失败的回调时,怎么会这样?我怎样才能解决这个问题?我希望能够多次接收数据。
以下代码基于对其他问题Yelp API and AngularJS的回答,不同之处在于评论正下方的陈述
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="oauth-signature.js"></script>
</head>
<body ng-app="plunker">
<div ng-controller="MainCtrl">
<p><date-input name="info.name" message="info.message"></date-input></p>
<ul>
<li data-ng-repeat="business in businesses">
{{business.name}}
</li>
</ul>
</div>
<script>
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', 'MyYelpAPI', function($scope, MyYelpAPI) {
$scope.businesses = [];
// first time for the callback gets executed
MyYelpAPI.retrieveYelp('', function(data) {
console.log('callback1');
console.log('data');
$scope.businesses = data.businesses;
});
// the second time for the callback doesn't get executed
MyYelpAPI.retrieveYelp('', function(data) {
console.log('callback2');
$scope.businesses = data.businesses;
});
}]).factory("MyYelpAPI", function($http) {
return {
"retrieveYelp": function(name, callback) {
var method = 'GET';
var url = 'http://api.yelp.com/v2/search';
var params = {
callback: 'angular.callbacks._0',
location: 'San+Francisco',
oauth_consumer_key: '',
oauth_token: '',
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: new Date().getTime(),
oauth_nonce: randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'),
term: 'food'
};
var consumerSecret = '',
var tokenSecret = '',
var signature = oauthSignature.generate(method, url, params, consumerSecret, tokenSecret, { encodeSignature: false});
params['oauth_signature'] = signature;
$http.jsonp(url, {params: params})
.success(callback)
// second time fails
// data -> undefined; status -> 404
.error(function(data, status) {
console.log(data, status); // why is this happening?
});
}
}
});
</script>
</body>
</html>
答案 0 :(得分:0)
你应该这样做:
$http.jsonp("api.yelp.com/v2/search?callback=JSON_CALLBACK", yourParams)
.success(function() {
//success callback
})
.error(function(){
//error callback
}) ;