Ionic getting remote JSON data

2019-09-14 02:16发布

问题:

I tried the following code by coping the data from JSON link as an object. Everything was good. But when I really retrieve it remote from the server and test, it seems that I cannot get it display on the list. Can someone help ? I want to list the title,image and author on the home.html page. Appreciate if anyone can help. Still trying to learn.

I've tried getting other JSON $http.get('https://jsonplaceholder.typicode.com/posts') and it worked. But this particular one is a little difficult for me to understand why it is not parsing correctly. For the code to work, i need to have it on my phone in order to work also. I can see the JSON being downloaded and alerted. But, I don't know why still not seeing the data.

Please see my code as follows. http://codepen.io/ccrash/pen/VjNPkv

Home.html

<ion-view view-title="Dashboard">
  <ion-content class="padding">
    <h2>Ionic GET Json Example</h2>
      <ion-item ng-repeat="x in result[0].data.items">
      <div> {{x.title}} </div>
      <div> {{x.image[0]}} </div>
      <div> {{x.author}} </div>
    </ion-item>
  </ion-content> 
</ion-view> 

Controller

.controller('HomeCtrl', function($http, $scope, $ionicSideMenuDelegate) {

  $http.get('http://www.malaysiakini.com/c/en/news?alt=json')
    .success(function(data, status, headers,config){
      //console.log('data success');
      //console.log(data); // for browser console
      alert(JSON.stringify(data));
      $scope.result = data; // for UI
    })
    .error(function(data, status, headers,config){
      console.log(headers); 
      console.log('data error');
    })
    .then(function(result){
      things = result.data;
    });  

})

回答1:

It's a common issue. I see errors in browser console:

It's usually because you are request to a different domain than your page is on, browser will block your request for security consideration. According to my experience, you can use jsonp as your request data type or add Access-Control-Allow-Origin headers to the server's response.

See this question for more infomation