1. xhr与fetch异步编程的步骤,实例演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ajax和fetch请求</title>
</head>
<body>
<button onclick="fun()">ajax-GET获取数据</button>
<button onclick="fun1()">fetch获取数据</button>
<script>
function fun() {
//ajax请求数据
const url = "http://jsonplaceholder.typicode.com/users";
//实例化
const xhr = new XMLHttpRequest();
//响应类型
xhr.response = "json";
xhr.open("GET", url);
//请求回调
xhr.onload = () => console.log(xhr.response);
xhr.onerror = () => console.log("Error");
//发起请求
xhr.send();
}
//fetc请求
function fun1() {
const url = "http://jsonplaceholder.typicode.com/users";
fetch(url)
.then((response) => response.json())
.then((json) => console.log(json));
}
</script>
<!-- 默认script在浏览器环境下不支持模块,需要指定type -->
<script type="module">
// 导入单个模块
import { username, getUserName } from "./modules.js";
console.log(username, getUserName(username));
//导入统一模块
import { age, getAge } from "./modules.js";
console.log(age, getAge(age));
//别名导入
import { addr } from "./modules.js";
console.log(addr);
//默认导入
import User from "./modules.js";
const user = new User("nnd");
console.log(user.username);
console.log(user.getUsername(user.username));
</script>
<script>
// 接收混合导入成员,默认成员的命名,必须放在非默认的前面
// 默认导出成员,在导入时可以随意命名的,useremail只是巧合
import email, { username, hello } from "./modules.js";
console.log(email);
console.log(hello(username));
</script>
</body>
</html>
2. 模块成员导出与导入,别名使用场景与命名空间演示
//1.逐个导出
export let username = "Tim";
export function getUserName() {
return username;
}
//统一导出
let age = 18;
function getAge() {
return `${age}`;
}
export { age, getAge };
// 别名导出;
let address = "北京市";
export { address as addr };
//默认导出,导出的是一个声明
//只是导出一个值,不是声明,没有被 命名,由导入时重命名
//一个模块,只能有一个默认导出
export default class {
constructor(username) {
this.username = username;
}
getUsername() {
return `hello ${this.username}`;
}
}
let username = "龙";
function hello(username) {
return `hello${username}`;
}
let useremail = "dddkj@djked";
export { username, hello, useremail as default };