第一个AJAX调用XMLHttpRequest

第一个AJAX调用XMLHttpRequest

  • 创建对象,用于浏览器和服务器的通信,不需要刷新浏览器
js 复制代码
const request = new XMLHttpRequest();
  • 通过GET请求方式在API中请求数据
js 复制代码
request.open('GET', 'https://restcountries.com/v3.1/name/Russia');

注:我这里的API是在GitHub中找的,大家也可以找类似的API使用

上面API有讲解如何去请求数据

  • 然后就发送请求,之后直接打印响应的文本看一下是否可以请求到数据
js 复制代码
request.send();
console.log(request.responseText);
  • 当然请求是异步的,上面可能会由于数据没有准备好等请求返回不了我们想要的,所以使用load来监听数据的介绍js
js 复制代码
request.addEventListener('load', function () {
  console.log(request.responseText);
});
  • 之后我们在浏览器测试一下数据是否可以正常接收,返回的数据是以json的格式返回的,我们将其转换为JavaScript对象的形式,当然现在都是JSON的方式来返回数据,XML格式已经过时淘汰了
js 复制代码
request.addEventListener('load', function () {
  const data = JSON.parse(this.responseText);
  console.log(data);

之后我们编写一个HTML模版,之后会以卡片的形式来展现的网页中

这里先看一下,我们预设的HTML代码

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <script defer src="script.js"></script>
    <title>异步 JavaScript</title>
  </head>
  <body>
    <main class="container">
      <div class="countries">
        <!--
        <article class="country">
          <img class="country__img" src="" />
          <div class="country__data">
            <h3 class="country__name">COUNTRY</h3>
            <h4 class="country__region">REGION</h4>
            <p class="country__row"><span>👫</span>POP people</p>
            <p class="country__row"><span>🗣️</span>LANG</p>
            <p class="country__row"><span>💰</span>CUR</p>
          </div>
        </article>
        -->
      </div>
      <!-- <button class="btn-country">Where am I?</button> -->
      <div class="images"></div>
    </main>
  </body>
</html>

这里注释的代码就是我们要插入的HTML模版

  • 现在我们就开始制作HTML模板
js 复制代码
    const html = `
     <article class="country">
          <img class="country__img" src=${data[0].flags.png} />
          <div class="country__data">
            <h3 class="country__name">${data[0].name.common}</h3>
            <h4 class="country__region">${data[0].region}</h4>
            <p class="country__row"><span>👫</span>${(
              data[0].population / 1000000
            ).toFixed(0)} people</p>
            <p class="country__row"><span>🗣️</span>${data[0].languages.rus}</p>
            <p class="country__row"><span>💰</span>${
              data[0].currencies.RUB.name
            }</p>
          </div>
        </article>`;
  });

其中的参数来JavaScript对象找就行,很简单,这里不做详细赘述

  • 然后我们将我们的模板插入到HTML代码中
js 复制代码
 countriesContainer.insertAdjacentHTML('beforeend', html);
 countriesContainer.style.opacity = 1;

css的预设代码如下

css 复制代码
* {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

html {
  font-size: 62.5%;
  box-sizing: border-box;
}

body {
  font-family: system-ui;
  color: #555;
  background-color: #f7f7f7;
  min-height: 100vh;

  display: flex;
  align-items: center;
  justify-content: center;
}

.container {
  display: flex;
  flex-flow: column;
  align-items: center;
}

.countries {
  /* margin-bottom: 8rem; */
  display: flex;

  font-size: 2rem;
  opacity: 0;
  transition: opacity 1s;
}

.country {
  background-color: #fff;
  box-shadow: 0 2rem 5rem 1rem rgba(0, 0, 0, 0.1);
  font-size: 1.8rem;
  width: 30rem;
  border-radius: 0.7rem;
  margin: 0 3rem;
  /* overflow: hidden; */
}

.neighbour::before {
  content: 'Neighbour country';
  width: 100%;
  position: absolute;
  top: -4rem;

  text-align: center;
  font-size: 1.8rem;
  font-weight: 600;
  text-transform: uppercase;
  color: #888;
}

.neighbour {
  transform: scale(0.8) translateY(1rem);
  margin-left: 0;
}

.country__img {
  width: 30rem;
  height: 17rem;
  object-fit: cover;
  background-color: #eee;
  border-top-left-radius: 0.7rem;
  border-top-right-radius: 0.7rem;
}

.country__data {
  padding: 2.5rem 3.75rem 3rem 3.75rem;
}

.country__name {
  font-size: 2.7rem;
  margin-bottom: 0.7rem;
}

.country__region {
  font-size: 1.4rem;
  margin-bottom: 2.5rem;
  text-transform: uppercase;
  color: #888;
}

.country__row:not(:last-child) {
  margin-bottom: 1rem;
}

.country__row span {
  display: inline-block;
  margin-right: 2rem;
  font-size: 2.4rem;
}

.btn-country {
  border: none;
  font-size: 2rem;
  padding: 2rem 5rem;
  border-radius: 0.7rem;
  color: white;
  background-color: orangered;
  cursor: pointer;
}

.images {
  display: flex;
}

.images img {
  display: block;
  width: 80rem;
  margin: 4rem;
}

.images img.parallel {
  width: 40rem;
  margin: 2rem;
  border: 3rem solid white;
  box-shadow: 0 2rem 5rem 1rem rgba(0, 0, 0, 0.1);
}
  • 之后就能将漂亮的表格输出出来了

目前我们是通过硬编码的方式传入国家的名称,我们可以通过函数的方式来调用

js 复制代码
'use strict';

const btn = document.querySelector('.btn-country');
const countriesContainer = document.querySelector('.countries');

///
const getCountrydata = function (country) {
  const request = new XMLHttpRequest();
  request.open('GET', `https://restcountries.com/v3.1/name/${country}`);
  request.send();

  request.addEventListener('load', function () {
    const data = JSON.parse(this.responseText);
    console.log(data);
    const html = `
     <article class="country">
          <img class="country__img" src=${data[0].flags.png} />
          <div class="country__data">
            <h3 class="country__name">${data[0].name.common}</h3>
            <h4 class="country__region">${data[0].region}</h4>
            <p class="country__row"><span>👫</span>${(
              data[0].population / 1000000
            ).toFixed(0)} people</p>
            <p class="country__row"><span>🗣️</span>${data[0].languages.rus}</p>
            <p class="country__row"><span>💰</span>${
              data[0].currencies.RUB.name
            }</p>
          </div>
        </article>`;
    countriesContainer.insertAdjacentHTML('beforeend', html);
    countriesContainer.style.opacity = 1;
  });
};

getCountrydata('us');

这里和上面的显示画面是一样的

相关推荐
mldong3 小时前
你的 Vue3 项目也能有钉钉同款审批流设计器:npm 装包,10 分钟画出第一条审批流
前端·vue.js
2分钟速写快排3 小时前
什么是 RAG?如何用 RAG 实现一个用户记忆?
前端·后端·ai编程
passerby60614 小时前
如何自己造一个时间处理库
前端·javascript·github
走到天涯海角5 小时前
react里面的长列表渲染优化
前端·react.js·前端框架
小羊没烦恼!5 小时前
Hello Web API系列教程——Web API与国际化
java·服务器·前端·javascript·php
北岛贰5 小时前
迷茫焦虑期,我做了一个带支付带官网的 AI 聊天虚拟恋人 App
前端·人工智能·后端
mayaairi7 小时前
Vue2 组件通讯(三):全局事件总线、PubSub、插槽与组件实例属性
前端·javascript·vue.js
kyriewen7 小时前
面试官问我:AI 都能写代码了,前端凭什么还值 25K
前端·javascript·人工智能
风骏时光牛马8 小时前
AI源码分析:拆解模型底层实现逻辑
前端
BillKu8 小时前
全局样式变量:CSS 自定义属性(--border-color)和SCSS 变量($border-color)的说明
javascript·css·scss