Javascript 使用 angularJS 从 JSON url 获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14466881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting data from JSON url using angularJS
提问by Prajoth
I am really new to using AngularJS and Javascript. I need to get the totalResultsdata from a JSON source that looks like this:
我对使用 AngularJS 和 Javascript 真的很陌生。我需要从如下所示的 JSON 源中获取totalResults数据:
{
"queries": {
"request": [
{
"totalResults": "51"
}
]
}
}
Once I get the data, I need it to show up in a list using AngularJS. I have tried really hard using .ajax and .getJSON, but I am unable to get either of them to work, given my complete lack of knowledge on using JavaScript. I really appreciate your help! My AngularJS looks like this:
获得数据后,我需要使用 AngularJS 将其显示在列表中。我已经非常努力地使用 .ajax 和 .getJSON,但我无法让它们中的任何一个工作,因为我完全缺乏使用 JavaScript 的知识。我真的很感谢你的帮助!我的 AngularJS 看起来像这样:
function MyController($scope){
$scope.url = "https://www.googleapis.com/customsearch/v1?key=[MYKEY]&cx=[MYSECRETKEY]&q=flowers&alt=json&fields=queries(request(totalResults))";
$scope.newMessage = "";
$scope.messages = ["Steve Jobs - 515,000,000 results"];
$scope.add = function(){
$scope.messages.push($scope.newMessage);
};
}
}
In the HTML part, I have this:
在 HTML 部分,我有这个:
<input type="text" ng-model="newMessage">
<input type="submit" ng-click="add()" value="Click to find out!">
When the user clicks the button, I want the url to be called and the $scope.newMessageshould be the value in totalResults. Thanks for your help!
当用户单击按钮时,我希望调用 url 并且$scope.newMessage应该是 totalResults 中的值。谢谢你的帮助!
回答by Valentyn Shybanov
You can use $httpservice: Documentation
您可以使用$http服务:文档
So you can:
这样你就可以:
$scope.add = function(){
$http.get($scope.url).then(function(response) {
$scope.newMessage = response.data.queries.request.totalResults;
$scope.messages.push($scope.newMessage);
});
};
回答by Arshabh Agarwal
Read a little in $http service provided by AngularJS
阅读 AngularJS 提供的 $http 服务
here is the hint to the code that you would use
这是您将使用的代码的提示
$scope.add = function(){
$http.get(url).then(function(response){
queries = response.queries;
$scope.newMessage = queries.request.totalResults;
})
}
回答by Qu?nh MSO
See http://plnkr.co/edit/nZkYsxLHLvf3SZNiJKic?p=info
见http://plnkr.co/edit/nZkYsxLHLvf3SZNiJKic?p=info
Following your link, I just found one error:
按照您的链接,我刚刚发现一个错误:
var x = searchResults.split('.');
don't have function split() if i replace: x = "abc"
如果我替换,则没有函数 split():x = "abc"
the result : Steve Jobs - 515,000,000 results - a.b results dsgdfg - a.b results
结果:史蒂夫乔布斯 - 515,000,000 个结果 - ab 结果 dsgdfg - ab 结果

