前言
ajax 即 Asynchronous Javascript And XML,AJAX 不是一门的新的语言,而是对现有持术的综合利用。本质是在 HTTP 协议的基础上以异步的方式与服务器进行通信.
提示:以下是本篇文章正文内容,下面案例可供参考
一、AJAX五部曲
1.创建一个异步对象xmlhttp;
var xhr= new XMLHttpRequest();
new ActiveXObject("Microsoft.XMLHTTP"); //IE6以下
2.调用open方法设置请求方式和请求地址;
xhr.open(type,url);
3.设置请求头(post需要)
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
4.监听请求完成函数
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
}
}
通过onreadystatechange 事件来监听发送的状态变化,readyState状态为4时,.status为200请求结束成功
5.发送请求
xhr.send();
其中post请求方式传参数,直接写在send()里面,get请求参数则需要放在url地址的参数中。并通过urlencode的方式传参,也就是?隔开url和参数,然后多个参数用&连接,参数格式为:key=val。
二、案例
调用某易源的笑话接口:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.boss {
width: 300px;
height: 300px;
/* border: 1px solid red; */
text-align: center;
float: left;
}
.boss img {
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<!-- <div class="boss">
<img src="img/0.jpg" alt="">
</div> -->
</body>
<script>
var str = "";
var xhr = new XMLHttpRequest();
xhr.open("get", "https://route.showapi.com/341-2?showapi_appid=124345&showapi_sign=87510e6b80b0408e9f623f9c00ad1c7a&page=1&maxResult=20")
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(JSON.parse(xhr.response));
var list = JSON.parse(xhr.response)["showapi_res_body"].contentlist;
console.log(list);
for (var i = 0; i < list.length; i++) {
str += `
<div class="boss">
<img src="${list[i]["img"]}" alt="">
</div>
`
}
document.body.innerHTML += str;
}
}
xhr.send();
</script>
</html>

2894

被折叠的 条评论
为什么被折叠?



