如何使用JSON API随机更改网页的背景颜色?

时间:2019-07-20 08:15:19

标签: javascript html json

我想基于此json文件执行javascript onload来随机更改网页的背景颜色。

http://api.creativehandles.com/getRandomColor

1 个答案:

答案 0 :(得分:0)

// this function will be triggered when the page loads. Every time you refresh the page a new background color will be set because this function will be invoked 
window.addEventListener('load', function() {
   // fetch is in charge of getting the data from the API
   fetch('http://api.creativehandles.com/getRandomColor') // Call the fetch function passing the url of the API as a parameter
.then(function(response) {

             response.json().then(function(data){
                 let color = data["color"]; 
                document.body.style.backgroundColor = color;
             })

         })
.catch(function() {
    // This is where you run code if the server returns any errors
});
})

您还可以将所有提取逻辑提取到一个单独的函数中,并创建一个按钮,该按钮在单击时调用该函数,从而每次单击按钮时都会更改背景色