简体   繁体   中英

Access json file data

I've created a json file in the website myjson.com. Here's the url : json file

Now when I try to access data like this : https://api.myjson.com/bins/udmp1/dishes , it doesn't work. But localy It works perfectly.

Now the code I'm using :

.constant("baseURL", "https://api.myjson.com/bins/udmp1")
.service('dishesFactory', ['$resource', 'baseURL', function ($resource, baseURL) {

    return $resource(baseURL + "dishes/:id", null, {
        'update': {
            method: 'PUT'
        }
    });

           }])

What did I do wrong ?

Thank you!

If You want to get dishes data, You should do next:

 $.get('https://api.myjson.com/bins/udmp1', function (a){ var dishesList = $('ul#dishes'); $.each(a.dishes, function (c,d){ dishesList.append("<li>"+d.name+"</li>") }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Dishes</p> <ul id="dishes"> </ul> 

As Content-Type of this response is application/json - no need to do a = JSON.parse(a) to get parsed data as object.

a - it's a response promise object, that You can proceed after response will come.

As per AngularJS , You should do next:

 var app = angular.module('testMod', []); app.controller('TestController', function ($scope, $http){ $http.get('https://api.myjson.com/bins/udmp1').then(function (a){ $scope.dishes = a.data.dishes; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <body ng-app="testMod"> <div ng-controller="TestController" > <ul> <li ng-repeat="dish in dishes" ng-bind="dish.name"></li> </ul> </div> 

you should request the url and assign it as object in javascript and then you can access the property like this:

$.ajax({
   url:  "https://api.myjson.com/bins/udmp1",
   method: "get",
   dataType: "json",
   success: function(data){
       var dishes = data.dishes; // now you get dishes
   }
})

Try this :

 var myApp = angular.module('myApp',[]); myApp.controller('FetchCtrl',function($scope, $http) { $scope.method = 'GET'; $scope.url = 'https://api.myjson.com/bins/udmp1'; $http({method: $scope.method, url: $scope.url}). success(function(res) { $scope.dishes = res.dishes; console.log($scope.dishes); // dishes data }). error(function(err) { console.log(err); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="FetchCtrl"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM