简体   繁体   中英

How can I combine multiple JSON data requests using jquery?

I am making a personal NEWS website. In my website I have made different sections like Tech,Sports,Business,General News. I am making different requests to different NEWS API using getJSON() in jquery.

Here is my code in my code you can see only source=" " is changing:

$.getJSON('https://newsapi.org/v1/articles?source='some-source'&sortBy=top&apiKey=myapi-key',function(json) {
        console.log(json);
    });

  $.getJSON('https://newsapi.org/v1/articles?source='some-source'&sortBy=top&apiKey=myapi-key',function(json) {
            console.log(json);
        });

  $.getJSON('https://newsapi.org/v1/articles?source='some-source'&sortBy=top&apiKey=myapi-key',function(json) {
                console.log(json);
            });

Each JSON data gives 4 to 5 objects(see screenshot for clarification) but that is not sufficient for my website so I am making multiple requests to API so that I can display many articles. Can you please suggest me is this right way to do as I have seen many forums and tutorials, they say repeating your code is bad practice.

JSON response:

在此处输入图片说明

You can make a function and pass the different API sources to the function as shown below, thus not rewriting your code. Hopefully this helps

function getNewsFeed(var url) {
    $.getJSON(url, function(json) {
        console.log(json);
    });
}

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