Ajax 的初步实现(使用vscode+node.js+express框架)(ajax的实现方法)不要告诉别人

随心笔谈12个月前发布 admin
96 0


<!DOCTYPE html>
<html lang=”en”>

<head>
<meta charset=”UTF-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=, initial-scale=1.0″>
<title>AJAX GET 请求</title>
<script src=”https://www.jb51.net/js/jquery-3.0.0.min.js”></script>
<style>
#result {
width: 200px;
height: 100px;
border: solid 1px red;
}
</style>
</head>

<body>
<button>发送请求</button>
<div id=”result”></div>
</body>
<script>
// 1.获取元素 给按钮添点击事件
$(‘button’).on(‘click’, function () {
// alert(1);
// 2.创建对象
const xhr=new XMLHttpRequest();
// 3.初始化 设置请求方式 和url
xhr.open(‘GET’, ‘http://127.0.0.1:8000/server’);
// 4.发送
xhr.send();
// 5.事件绑定 处理服务器返回的结果
xhr.onreadystatechange=function () {
// readystate 是 xhr 对象中的属性 有 0 1 2 3 4
// 判断(4 表示服务端返回了所有的结果)
if (xhr.readyState==4) {
if (xhr.status >=200 && xhr.status < 300) {
// 处理结果有: 行 头 空行 体
// 1.响应行
// 2.将响应体 返回到客户端页面中
$(‘div’).html(xhr.response);
}

}
else {

}
}
})
</script>

</html>

© 版权声明

相关文章