原生
<script>
//创建异步对象
const xhr=new XMLHttpRequest()
//设置url和发送方式
xhr.open('GET',"https://api-hmugo-web.itheima.net/api/public/v1/goods/search")
//发送请求
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState==4 &&xhr.status==200) {
console.log(JSON.parse(xhr.responseText));
}
}
</script>
jquery
<script>
$.ajax({
type:"GET",
url:"https://api-hmugo-web.itheima.net/api/public/v1/goods/search",
success:function(e){
console.log(e);
}
})
</script>
fetch
<script>
window.onload = function () {
fetch("https://api-hmugo-web.itheima.net/api/public/v1/goods/search", {
method: "GET"
})
// .then(res=>res.json())
// .then(res=>console.log(res))
.then(res =>res.json())
.then(data => {
console.log(data);
})
}
</script>
promise结合ajax
<!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>Document</title>
</head>
<body>
</body>
</html>
<script>
new Promise(function (resolve, reject) {
console.log("promise执行");
resolve()
})
.then(function () {
const xhr = new XMLHttpRequest()
//设置url和发送方式
xhr.open('GET', "https://api-hmugo-web.itheima.net/api/public/v1/goods/search")
//发送请求
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(JSON.parse(xhr.responseText));
}
}
}).then(function(){
setTimeout(() => {
console.log("第二个then");
}, 1000);
})
.catch(function () {
console.log("我是catch");
})
</script>
ayse await
<!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>Document</title>
</head>
<body>
</body>
</html>
<script>
//创建异步对象
function myajax(url){
const xhr=new XMLHttpRequest()
//设置url和发送方式
xhr.open('GET',url)
//发送请求
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState==4 &&xhr.status==200) {
console.log(JSON.parse(xhr.responseText));
}
}
}
async function aa(){
const res=await myajax("https://api-hmugo-web.itheima.net/api/public/v1/goods/search")
}
window.onload=aa()
</script>