AJAX
AJAX
不需要加载整个页面,局部刷新
在项目的根初始化
npm inin -y
生成一个json的配置项目,注意:配置文件是json对象,不要在里面写注释之类的
{
"name": "ajax",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
-
script字段
"dev": "node index.js"
-
main :项目入口
-
dependencies:当项目中要依赖其他模块,就会在dependencies中记录,为了以后项目下载
下载需要的模块
在根目录下
npm i 模块名
有的时候可能会出现丢包的情况,找不到模块,可以删除下载的模块后,重新下载
前端刷新页面两种技术
- 跳转到一个新的html页面
- 局部刷新,用js去做网络请求得到数据,动态的渲染DOM
ajax的技术封装到了window.XMHttpRequest()构造函数里面
AJAX请求
let xhr = new XMLHttpRequest()||new ActiveXObject("Microsoft.XMLHTTP")
配置连接信息
xhr.open('GET',"/ajax1?name=lei")
发送网络请求
xhr.send()
监听网络状态
xhr.onreadystatechange = function() {
if(xhr.readyState==4&&xhr.state == 200) {
console.log('发送完毕')
console.log(xhr.responseText)
}
}
取出数据
把JSON数据写成UI页面
回调封装AJAX
tool函数一般是执行任务的函数,当这个任务执行完毕时调用传入的callback函数
<body>
<button id="box">kuayu</button>
</body>
<script>
function setDataToUI(str) {
let obj = JSON.parse(str)
console.log(obj.data)
}
function tool(url,cb) {
// 过程
let xhr = new XMLHttpRequest() || new ActiveXObject()
xhr.open('GET',url)
xhr.send()
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
// console.log(xhr.responseText)
cb(xhr.responseText)
}
}
}
var button = document.querySelector('#box')
button.onclick = function() {
tool('http://127.0.0.1:8080/ajax',setDataToUI)
}
</script>
axios
promise封装AJAX
// myaxious 网络请求 返回Promise对象
function myaxios(url) {
let p = new Promise((n1,n2)=> {
let xhr = new XMLHttpResquest()
xhr.open("GET","url",true)
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
n1(xhr.responseText)
}
}
})
}
function fn() {
myaxios(url).then((res)=> {
console.log(res)
})
}