ajax : 客户端向服务器端请求数据的一种技术
同步:客户端向服务器端发送请求的时候,用户不能进行其他操作
异步:客户端向服务器端发送请求的时候,用户可以进行其他操作
以及对资源的操作肯定是异步的
没封装的http
<p id="app">
</p>
<script>
/*
1.什么是异步 何时使用
2.如何使用原生ajax
*/
var app = document.getElementById("app")
var url ="http://192.168.4.18:8000/"
/* ajax 如何使用ajax向后台获取数据*/
/* 1. 创建ajax核心对象*/
var xhr = new XMLHttpRequest();
/* 2.与服务器建立连接 xhr.open(method,url,async)
请求的方式,地址,是否异步
*/
xhr.open("get",url,true)
/* 3.发送请求 */
xhr.send()
/* 4.响应 */
/* onreadystatechange 监听服务器的响应状态*/
xhr.onreadystatechange = function(){
/* xhr.status 服务器端响应的状态码 200 */
/* xhr.readyState 服务器响应的进度 4 响应已经完成 */
if(xhr.readyState == 4 && xhr.status == 200){
var txt = xhr.responseText;
/* JSON.parse() 可以json格式的字符串,转换为json格式的数据 */
var obj = JSON.parse(txt);
console.log(obj)
app.innerHTML = obj.name
}
}
</script>
http.js
function ajax({
url,
method,
success
}){
var xhr = new XMLHttpRequest()
xhr.open(method,url,true)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var res = JSON.parse(xhr.responseText);
success(res);
}
}
}
传参(解构)
function http({
callback:callback,
method,
url,
}) {
console.log(callback);
console.log(method)
console.log(url)
}
http({
callback:"123",
method:"get",
url:"xx"
})
封装ajax
<script src="js/http.js"></script>
var url = "http://192.168.4.18:8000/"
ajax({
url,
method:"get",
success:res=>{
console.log(res)
}
})
index.js
const koa = require("koa");
const app = new koa;
const router = require("koa-router")();
const cors = require("koa2-cors");
app.use(cors());
router.get("/",async ctx=>{
ctx.body ={
name:"html",
age:13,
code:200
}
})
app.use(router.routes());
app.listen(8000)