简体   繁体   中英

getting JSON data from REST API by javascript displays partial data

I am trying to get data from alchemynewsapi through javascript. The sample data i receive is:

{
"status": "OK",
"totalTransactions": "68",
"result": {
    "docs": [
        {
            "id": "ODU1MjM4MjM0NnwxNDQ5MDk0Mzgy",
            "source": {
                "enriched": {
                    "url": {
                        "title": "North Scituate observatory hosts workshop on telescopes",
                        "url": "http://www.providencejournal.com/article/20151201/entertainmentlife/151209982"
                    }
                }
            },
        {
            "id": "ODEzMzYxODU5MHwxNDQ5MDYyMjM0",
            "source": {
                "enriched": {
                    "url": {
                        "title": "Mob Programming Workshop",
                        "url": "https://www.eventbrite.com/e/mob-programming-workshop-tickets-19710798529"
                    }
                }
            },
            "timestamp": 1449062234
        }
    ],
    "next": "MzY5OTc0NjQzNzI2MjMxNzM2N3xPREU1TnpnNU9EWXhPSHd4TkRRNU1EWTNPVFE1",
    "status": "OK"
   }
}

I am trying the following for retrieving title and url fields of the data:

var jsonData=getJSON('http://urlofapi').then(function(data) {
for(var i=0; i<data.result.docs.length; i++)
 {
     result.innerText = data.result.docs[i].source.enriched.url.title; //for retrieving the title field
 }
}, function(status) { //error detection....
alert('Something went wrong.');
});

getJSON is a function i have created :

var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status == 200) {
    resolve(xhr.response);
  } else {
    reject(status);
  }
};
xhr.send();
});
};

But it only displays me the last title of the data ie here the "Mob..."

What needs to be done to retrieve all the titles if there are 100's of items?

It's quite normal, your code has:

result.innerText = data.result.docs[i].source.enriched.url.title; //for retrieving the title field

Which means you constantly replace the contents of result with a new title, so at the end, you display the last one.

You need to concatenate the data somehow, or use console.log if you're just trying to see the results before doing something more with them.

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