如何使用REST API创建Covid19国家状态项目

如何使用REST API创建Covid19国家状态项目

今天,世界上所有国家都在与冠状病毒作斗争。每天,冠状病毒病例都在迅速增加。所有的人都必须每天跟踪COVID病例,并应努力保持自己的安全。我们已经制作了小型的网络应用程序,它将告诉你总的病例数、新病例、新死亡病例、康复情况等,供用户参考。你只需输入国家名称并点击搜索即可。

这个应用程序也受到保护,不受客户端脚本的影响,并使用免费的Covid19 API。以下是API的链接。
https://covid19api.com/

运行程序的步骤:我们在本文中展示了JavaScript和HTML文件。所有的代码包括HTMLCSS、js都在我的Github档案中。以下是完整的项目链接。
https://github.com/rohitdhonicsk/covid19webapp

  1. Git clone https://github.com/rohitdhonicsk/covid19webapp ,将GitHub项目文件复制到你的电脑上。
  2. 现在打开Index.html文件。
  3. 输入国家名称并点击搜索。

需要的项目文件和模块:

  1. 你应该有三个主要文件index.html(下面是index.html文件的代码),CSS(只有在你想设计的时候才需要,你可以从我的GitHub仓库项目文件中下载CSS)。第三个最重要的文件是JavaScript文件(我们在下面给出了完整的代码),它需要用来获取COVID数据和响应用户搜索。
  2. 你需要jQuery,这是一个JavaScript库。你可以从Jquery官方网站上把CDN脚本放到你的HTML代码中,或者使用下面的命令。

注意:确保你在机器上安装了NODE和NPM,否则请到节点的官方网站上下载和安装。

首先,你必须在项目目录中输入以下命令。它将创建一个package.json文件。

npm init

现在输入以下命令来安装jQuery

npm install jquery

Project Directory:
如何使用REST API创建Covid19国家状态项目?

该项目将看起来像这样:
Home Page:
如何使用REST API创建Covid19国家状态项目?

COVID19的统计搜索:印度 国家:
如何使用REST API创建Covid19国家状态项目?

建立应用程序的步骤:

  1. 第一步是进入API,将API的链接复制到postman应用程序中,并将JSON格式的数据可视化。我们正在使用API的摘要数据。
  2. 在HTML文件中创建一个表格,输入栏是国家名称。
  3. 为标题、表单、输入和标签分配标识,这些标识应在JavaScript上使用。下面是演示的HTML文件,该文件中的class和id被用于样式设计和动作调用。
<h1 class='section-heading'>COVID RESULT</h1>
<h2 class='section-subheading'>SEARCH COUNTRY NAME</h2>
  
<div class="section-description">
  
  <p class="section-subheading">
  <form id="query-form">
    <div>
      <label for="ingredients">Country :</label>
        <input class="textfield" id="ingredients" 
          type="text" name="ingredients"
          placeholder="e.g.India, chiNA" 
          onChange="sanitizeInputs()" />
    </div>
  
    <div class="button">
      <br />
      <input class="button" type="button" 
        value="Reset" id="resetButton" 
        onClick="this.form.reset();resetResults()" />
      <input class="button" type="submit" 
        value="Search ..." id="searchButton" />
    </div>
  </form>
  </p>
  
  <div class="section-subheading" 
    id="search-results-heading"></div>
  <div class="results-div" id="results"></div>
</div>
  1. 现在包括你的CSS文件(它是可选的)。
  2. 记住在HTML代码中包括以下两点。

* jQuery CDN链接
* 你的JS文件
6. 现在,在你的JS文件中添加以下代码。

// This Code calls function name performSearch()
// on clicking submit button of form 
  
(document).ready(function() {
  
  // Add an event listener (performSearch) 
  // to the form
  ("#query-form").submit(function(event) 
    { performSearch(event); });
});
  1. 现在使用以下代码创建 performSearch() 函数。
function performSearch(event) {
  
  // Variable to hold request
  var request;
  
  // Prevent default posting of form 
  // put here to work in case of errors
  event.preventDefault();
  
  // Abort any pending request
  if (request) {
      request.abort();
  }
  
  // Setup some local variables
  var form =(this);
  
  // Disable the inputs and buttons 
  // for the duration of the request.
  setFormDisabledProps(true);
  
  // It will show heading searching during the request
  ("#search-results-heading").text("Searching ...");
  ("#results").text("");
  
  // Send the request to API for data
  request = .ajax({
      url:"https://api.covid19api.com/summary",
      type: "GET",
      // data: { i:, q:("#contains").val()}
  });
  
// Taking country name from input box that we created
pat=("#ingredients").val(); 
  
  // Callback handler for success
  request.done(function (response, textStatus, jqXHR) {
      
    // Calling formal search after getting data from api
    formatSearchResults(response);
  });
  
  // Callback handler for failure
  request.fail(function (jqXHR, textStatus, errorThrown) {
   ("#search-results-heading").
     text("Unable to fetch Covid Data, Try again")
   $("#results").text("");
  });
  
  // Callback handler that will be called in any case
  request.always(function () {
  
      // Reenable the inputs
      setFormDisabledProps(false);
  });
}

8.创建formatSearchResults函数,给用户提供想要的搜索结果。

var pat, flag = 0;
    function formatSearchResults(jsonResults) {
      
        // Storing Json Data in jsonobject variable
        var jsonObject = jsonResults;
      
        ("#search-results-heading").text("Search Results");
        var formatedText = "";
      
        jsonObject.Countries.forEach(function (item, index) {
      
            // Matching user search data with api data 
            if (item.Country.toLowerCase() == pat.toLowerCase()) {
                var thumbnail = item.NewConfirmed;
      
                // Printing the result
                formatedText += 
    "<div class='dish-ingredients-div'><h3>TotalConfirmed: " +
                    item.TotalConfirmed + "<h3></div>";
      
                formatedText += 
    "<div class='dish-ingredients-div'><h3>NewDeaths: " +
                    item.NewDeaths + "<h3></div>";
      
                formatedText += 
    "<div class='dish-ingredients-div'><h3>NewConfirmed: " +
                    item.NewConfirmed + "<h3></div>";
      
                formatedText += 
    "<div class='dish-ingredients-div'><h3>NewRecovered: " +
                    item.NewRecovered + "<h3></div>";
      
                flag = 1;
                return;
            }
        });
      
        // If result not found
        ("#results").html(formatedText);
      
        if (!flag) {
            ("#search-results-heading")
                .text("Dont Fun With it.Please Enter"
                + " Correct Country Name e.g-India");
            ("#results").text("");
        }
    }
  1. 而最后一步是保护数据不受客户端脚本和重置功能的影响。
function resetResults() {
  ("#search-results-heading").text("");
  ("#results").text("");
  flag=0;
}
  
// This function checks the user input fields
// for any unacceptable characters and removes
// them if found
function sanitizeInputs() {
  var str = ("#ingredients").val();
  str = str.replace(/[^a-zA-Z 0-9, ]/gim, "");
  str = str.trim();
  ("#ingredients").val(str);
}

完整的Javascript代码:

// This Code call function name performSearch()
// on clicking submit button of form 
(document).ready(function () {
  
    // Add an event listener (performSearch)
    // to the form
    ("#query-form").submit(function (event) 
        { performSearch(event); });
});
  
var pat, flag = 0;
function formatSearchResults(jsonResults) {
  
    // Storing Json Data in jsonobject variable
    var jsonObject = jsonResults;
  
    ("#search-results-heading").text("Search Results");
    var formatedText = "";
  
    jsonObject.Countries.forEach(function (item, index) {
  
        // Matching user search data with api data 
        if (item.Country.toLowerCase() == pat.toLowerCase()) {
            var thumbnail = item.NewConfirmed;
            // Printing the result
            formatedText += 
"<div class='dish-ingredients-div'><h3>TotalConfirmed: " +
                item.TotalConfirmed + "<h3></div>";
  
            formatedText += 
"<div class='dish-ingredients-div'><h3>NewDeaths: " +
                item.NewDeaths + "<h3></div>";
  
            formatedText += 
"<div class='dish-ingredients-div'><h3>NewConfirmed: " +
                item.NewConfirmed + "<h3></div>";
  
            formatedText += 
"<div class='dish-ingredients-div'><h3>NewRecovered: " +
                item.NewRecovered + "<h3></div>";
  
            flag = 1;
            return;
        }
    });
  
    ("#results").html(formatedText);
  
    // If result not found
    if (!flag) {
        ("#search-results-heading")
            .text("Dont Fun With it.Please Enter"
                + " Correct Country Name e.g-India");
        ("#results").text("");
    }
}
  
function performSearch(event) {
  
    // Variable to hold request
    var request;
  
    // Prevent default posting of form - 
    // put here to work in case of errors
    event.preventDefault();
  
    // Abort any pending request
    if (request) {
        request.abort();
    }
  
    // Setup some local variables
    var form =(this);
  
    // Disable the inputs and buttons 
    // for the duration of the request.
    setFormDisabledProps(true);
  
    // It will show heading searching
    // during the request
    ("#search-results-heading")
            .text("Searching ...");
    ("#results").text("");
  
    // Send the request to API for data
    request = .ajax({
        url: "https://api.covid19api.com/summary",
        type: "GET",
        // data: { i:, q:("#contains").val() }
    });
  
    // Taking country name from input
    // box that we created
    pat = ("#ingredients").val();
  
    // Callback handler for success
    request.done(function (response, 
        textStatus, jqXHR) {
        formatSearchResults(response);
    });
  
    // Callback handler for failure
    request.fail(function (jqXHR, 
            textStatus, errorThrown) {
  
        // Calling formal search after 
        // getting data from api
        ("#search-results-heading").text(
"Sorry We Unable to fetch Covid Data.Try again.");
        ("#results").text("");
    });
  
    // Callback handler that will be
    // called in any case
    request.always(function () {
  
        // Reenable the inputs
        setFormDisabledProps(false);
    });
}
  
// This function clears the search results
// and the heading "Search Results"
function resetResults() {
    ("#search-results-heading").text("");
    ("#results").text("");
    flag = 0;
}
  
// This function checks the user input
// fields for any unacceptable characters
// and removes them if found
function sanitizeInputs() {
    var str =("#ingredients").val();
    str = str.replace(/[^a-zA-Z 0-9, ]/gim, "");
    str = str.trim();
    $("#ingredients").val(str);
}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程