Jag kommer att visa dig hur du hämtar data med hjälp av ren JavaScript (VanillaJS) i denna handledning. Jag kommer att göra en förfrågan till en slutpunkt, hantera svaret och visa hämtad information. Den data som mottas i en begäran kan vara i vilket format som helst (XML, JSON, HTML, MP3, MP4), jag kommer att hämta HTML-data i den här handledningen.
XMLHttpRequest (XHR) används i JavaScript för att interagera med servrar. XMLHttpRequest kan användas för all typ av data, det är inte bara XML som namnet antyder. HTTP definierar flera metoder som beskriver den åtgärd som kommer att utföras på servern. GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT och PATCH är metoder som kan finnas i servermetoder. Om vi vill hämta data får vi bara anropa servermetoder som deklareras som en GET-metod. CORS måste vara aktiverat på slutpunkten för att vi ska kunna göra anrop från JavaScript.
Den här koden har testats och fungerar med Google Chrome (75.0.3770.100), Mozilla Firefox (67.0.4), Microsoft Edge (42.17134.1.0), detta utan någon polyfill. Koden fungerar i Internet Explorer (11.829.17134.0) med en polyfill för XMLHttpRequest. Om du vill stödja äldre webbläsare kan du läsa vårt inlägg om transpilering och komplettering av JavaScript.
HTML-mall
@using Annytab.Repositories
@using Annytab.Models
@inject IGroupRepository group_repository
@{
// Get a group
Group group = ViewBag.Group;
IList<TeamInGroupStanding> teams = this.group_repository.GetTeamsFromXml(group.data_content);
Int32 rowCounter = 0;
}
@*Get teams in the group*@
<a href="@("https://www.hockeytabeller.se/home/group/" + group.page_name)" rel="nofollow" class="annytab-ht-not-hover">
<div class="annytab-ht-table">
<div class="annytab-ht-row">
<div class="annytab-ht-col-th-normal">RK</div>
<div class="annytab-ht-col-th-wide">Lag</div>
<div class="annytab-ht-col-th-normal">GP</div>
<div class="annytab-ht-col-th-normal">TP</div>
</div>
@for (int j = 0; j < teams.Count; j++)
{
@if (teams[j].name == "")
{
<div class="annytab-ht-row">
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
</div>
}
else
{
rowCounter++;
<div class="@(rowCounter % 2 != 0 ? "annytab-ht-row-main" : "annytab-ht-row-alt")">
<div class="annytab-ht-col-normal">@((rowCounter).ToString())</div>
<div class="annytab-ht-col-wide">@teams[j].name</div>
<div class="annytab-ht-col-normal">@teams[j].games</div>
<div class="annytab-ht-col-normal">@teams[j].points</div>
</div>
}
}
</div>
</a>
API-metod
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using Annytab.Repositories;
using Annytab.Models;
namespace Hockeytabeller.Api
{
/// <summary>
/// This class handles groups
/// </summary>
[Route("api/groups/[action]")]
public class GroupsController : Controller
{
#region Variables
private readonly ILogger logger;
private readonly IGroupRepository group_repository;
#endregion
#region Constructors
/// <summary>
/// Create a new controller
/// </summary>
public GroupsController(ILogger<GroupsController> logger, IGroupRepository group_repository)
{
// Set values for instance variables
this.logger = logger;
this.group_repository = group_repository;
} // End of the constructor
#endregion
#region Get methods
// Get html by page name
// GET api/groups/get_overview_as_html/shl
[HttpGet("{id}")]
[Microsoft.AspNetCore.Cors.EnableCors("AnyOrigin")]
[ResponseCache(Duration = 3600, Location = ResponseCacheLocation.Any)]
public IActionResult get_overview_as_html(string id = "")
{
// Get a group
Group group = this.group_repository.GetOneByPageName(id);
// Create view data
ViewDataDictionary view_data = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
view_data.Add("Group", group);
// Return a partial view
return new PartialViewResult { ViewName = "Views/home/_group_table.cshtml", ViewData=view_data, ContentType="text/html" };
} // End of the get_overview_as_html method
#endregion
} // End of the class
} // End of the namespace
JavaScript
Koden nedan används för att skapa en förfrågan om att hämta HTML-data från en API-metod. Den mottagna informationen visas under koden. Använd Chrome DevTools för att kontrollera svar och loggar.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
<style>
.annytab-ht-not-hover {
text-decoration: none;
}
.annytab-ht-table {
display: table;
width: 100%;
padding: 0px;
margin: 0px;
font-family: Arial, Helvetica, sans-serif;
background-color: #ffffff;
color: #000000;
overflow: hidden;
}
.annytab-ht-row {
display: table-row;
}
.annytab-ht-row-main {
display: table-row;
background-color: #ffffff;
}
.annytab-ht-row-alt {
display: table-row;
background-color: #f0f0f0;
}
.annytab-ht-col-th-normal {
display: table-cell;
padding: 4px;
color: #3d3d3d;
border-bottom: 1px solid #9e9e9e;
border-top: 1px solid #9e9e9e;
font-size: 14px;
line-height: 18px;
vertical-align: middle;
text-align: center;
width: 20%;
}
.annytab-ht-col-th-wide {
display: table-cell;
padding: 4px;
color: #3d3d3d;
border-bottom: 1px solid #9e9e9e;
border-top: 1px solid #9e9e9e;
font-size: 14px;
line-height: 18px;
vertical-align: middle;
text-align: left;
width: 40%;
}
.annytab-ht-col-line {
display: table-cell;
height: 1px;
background-color: #000000;
padding: 0px;
}
.annytab-ht-col-normal {
display: table-cell;
padding: 4px;
font-size: 12px;
line-height: 12px;
word-break: break-word;
vertical-align: middle;
text-align: center;
}
.annytab-ht-col-wide {
display: table-cell;
padding: 4px;
font-size: 12px;
line-height: 12px;
word-break: break-word;
vertical-align: middle;
text-align: left;
}
</style>
</head>
<body style="width:100%;font-family:Arial, Helvetica, sans-serif;padding:20px;">
<div class="hockeytabeller.se" data-group="shl"></div>
</body>
</html>
<script>
// Initialize when DOM content has been loaded
document.addEventListener('DOMContentLoaded', function () {
var elements = document.getElementsByClassName('hockeytabeller.se');
for (var i = 0; i < elements.length; i++) {
get_group(elements[i]);
}
}, false);
// Get a group
function get_group(element)
{
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.hockeytabeller.se/api/groups/get_overview_as_html/' + element.getAttribute('data-group'), true);
xhr.onload = function ()
{
// Success status codes can also be 201, 202, 203, 204 and more
if (xhr.status === 200)
{
element.insertAdjacentHTML('beforeend', xhr.response);
}
else
{
// Log error information
console.log(xhr.status + " - " + xhr.statusText);
}
};
xhr.onerror = function ()
{
// Log error information
console.log(xhr.status + " - " + xhr.statusText);
};
xhr.send();
} // End of the get_group method
</script>
Svar
<a href="https://www.hockeytabeller.se/home/group/shl" rel="nofollow" class="annytab-ht-not-hover">
<div class="annytab-ht-table">
<div class="annytab-ht-row">
<div class="annytab-ht-col-th-normal">RK</div>
<div class="annytab-ht-col-th-wide">Lag</div>
<div class="annytab-ht-col-th-normal">GP</div>
<div class="annytab-ht-col-th-normal">TP</div>
</div>
<div class="annytab-ht-row-main">
<div class="annytab-ht-col-normal">1</div>
<div class="annytab-ht-col-wide">Luleå HF</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">106</div>
</div>
<div class="annytab-ht-row-alt">
<div class="annytab-ht-col-normal">2</div>
<div class="annytab-ht-col-wide">Färjestad BK</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">92</div>
</div>
<div class="annytab-ht-row-main">
<div class="annytab-ht-col-normal">3</div>
<div class="annytab-ht-col-wide">Rögle BK</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">92</div>
</div>
<div class="annytab-ht-row-alt">
<div class="annytab-ht-col-normal">4</div>
<div class="annytab-ht-col-wide">Skellefteå AIK</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">90</div>
</div>
<div class="annytab-ht-row-main">
<div class="annytab-ht-col-normal">5</div>
<div class="annytab-ht-col-wide">HV 71</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">89</div>
</div>
<div class="annytab-ht-row-alt">
<div class="annytab-ht-col-normal">6</div>
<div class="annytab-ht-col-wide">Djurgårdens IF</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">88</div>
</div>
<div class="annytab-ht-row">
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
</div>
<div class="annytab-ht-row-main">
<div class="annytab-ht-col-normal">7</div>
<div class="annytab-ht-col-wide">Frölunda HC</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">85</div>
</div>
<div class="annytab-ht-row-alt">
<div class="annytab-ht-col-normal">8</div>
<div class="annytab-ht-col-wide">Örebro HK</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">85</div>
</div>
<div class="annytab-ht-row-main">
<div class="annytab-ht-col-normal">9</div>
<div class="annytab-ht-col-wide">IF Malmö Redhawks</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">77</div>
</div>
<div class="annytab-ht-row-alt">
<div class="annytab-ht-col-normal">10</div>
<div class="annytab-ht-col-wide">Växjö Lakers HC</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">70</div>
</div>
<div class="annytab-ht-row">
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
</div>
<div class="annytab-ht-row-main">
<div class="annytab-ht-col-normal">11</div>
<div class="annytab-ht-col-wide">Linköping HC</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">65</div>
</div>
<div class="annytab-ht-row-alt">
<div class="annytab-ht-col-normal">12</div>
<div class="annytab-ht-col-wide">Brynäs IF</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">60</div>
</div>
<div class="annytab-ht-row">
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
<div class="annytab-ht-col-line"></div>
</div>
<div class="annytab-ht-row-main">
<div class="annytab-ht-col-normal">13</div>
<div class="annytab-ht-col-wide">Leksands IF</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">49</div>
</div>
<div class="annytab-ht-row-alt">
<div class="annytab-ht-col-normal">14</div>
<div class="annytab-ht-col-wide">IK Oskarshamn</div>
<div class="annytab-ht-col-normal">52</div>
<div class="annytab-ht-col-normal">44</div>
</div>
</div>
</a>