ajax
本质:一个服务器与浏览器之间的代理
使用
get请求
//创建ajax对象 const xhr = new XMLHttpRequest() const params = "?name=llr&age=18" ////参数一:请求方式类型|参数二:请求同源地址+参数 xhr.open('get','http://localhost:3000/jack'+params) //发送请求 xhr.send() //获取资源 xhr.onload=function(){ console.log(JSON.parse(xhr.responseText)); }
post请求
document.querySelector('#btn').addEventListener('click',function () { const xhr = new XMLHttpRequest() const username = document.querySelector('#username').value; const age = document.querySelector('#age').value let params = `username=${username}&age=${age}` //POST请求发送方式 xhr.open('post',`http://localhost:3000/first`) //设置请求参数类型 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded') //POST请求参数传递方式 xhr.send(params) xhr.onload=function(){ console.log(JSON.parse(xhr.responseText)); } })
post传递json
document.querySelector('#btn').addEventListener('click',function () { xhr.open('post','http://localhost:3000/first') xhr.setRequestHeader('Content-Type','application/json'); xhr.send(JSON.stringify({name:'lisi',age:18})) xhr.onload=function(){ console.log(xhr.responseText); } })
请求参数|状态码
Content-Type,
-
application/x-www-form-urlencoded=>传统params(name=llr&age=18)
-
application/json=>json格式
注:传统表单和get请求只能接受application/x-www-form-urlencoded请求格式
-
通过xhr.status获取浏览器状态码(400),通过xhr.readyState获取ajax状态码
http状态码
通过xhr.status获取服务器状态码
404:检查客户端地址是否有误
500:检查后端数据是否出错
oonerror:请求无法发送到服务器(网络问题),并且会触发onerror事件
readyState
//目前已被onload事件代替
//状态码使用xhr.readyState获取,234状态码需要通过onreadystatechange事件监听变化
0:未初始化(没调用open)
1:请求已建立,未发送(没调用send)
2:请求已发送
3:请求处理中,部分数据可以使用
4:响应已完成,可以获取并使用服务器响应了
传统网站问题
-
网速慢,页面加载时间长
-
表单提交后,一项内容不合格,需要重新填写所有表单内容
-
页面跳转重定向,造成资源浪费
应用场景
-
页面上拉加载更多
-
列表数据无刷新分页
-
表单项离开焦点数据验证
-
搜索框提示文字下拉列表
JSONP
原理:利用script标签的src属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 客服端 <script> //客户端提前声明好函数,服务端返回声明好的函数执行,并在形参中传递参数 function request(params) { //params就是服务端传过来的数据,这里对他进行处理 console.log(params); } </script> <script src= 'http://localhost:3001' ></script> 服务端 <script> app.get( '/' ,(req,res)=>{ const fn = "request({name:'lisi',age:30})" res.send(fn) //也可以使用res.jsonp({name:'lisi',age:30}),不需要send就可以把数据传递过去 }) </script> |
func必须为全局函数
1 2 3 4 5 6 7 8 9 | 方式 $.ajax({ url: "127.0.0.1:8080" , method: "get" , dataType: "jsonp" , success:res=>{ console.log(res) } }) |
CORS
只需要在服务器中间件中设置res.header即可
app.use((req,res,next)=>{ res.header('Access-Control-Allow-Origin','*') res.header('Access-Control-Allow-Method','post,get') next() })
服务端跨域2
需要安装引用第三方模块request
const request = require('request') app.get('/',(req,res)=>{ request('http://localhost:3001/cross',(err,response,body)=>{ //err:错误对象,成功返回null //response:服务器端响应信息 //body:需要跨域获取的数据 res.send(body) }) })
跨域cookie
处于安全性考虑 ,跨域中cookie不会保存
客服端:xhr.withCredentials = true当发送跨域请求时,携带cookie信息
服务端:res.header('Access-Control-Allow-Credentials',true)
$.ajax
$.ajax({ type:'post', url:'/user', //会自动转换,如果是json需要自己json.strityfy(参数) data:JSON.stringify({username:'lisi'}), //默认contentType为'application/x-www-form-urlencoded' //如果需要将contentType改为json格式需要将data参数同时修改为json格式 contentType:'application/json', datatype:'jsonp', jsonp:'cb',//将地址中的callback改为cb beforeSend:function(){ //请求发送前调用 return false }, success:function(data){ console.log(data) }, error:function(err){ console.log(err) } })
参数一:地址|参数二:params(可选)|参数三:成功后的回调
$.get('http://www.example.com',{name:'zhangsan',age:30},function(){})
$.post('http://www.example.com',{name:'zhangsan',age:30},function(){})
全局事件
$(document).on('ajaxStart',function(){})
$(document).on('ajaxComplete',function(){})
服务端RESTful API
修改jQuery中ajax的type即可
get查询|post添加|delete删除|
【推荐】FlashTable:表单开发界的极速跑车,让你的开发效率一路狂飙
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· JavaScript中如何遍历对象?
· 领域模型应用
· 记一次 ADL 导致的 C++ 代码编译错误
· MySQL查询执行顺序:一张图看懂SQL是如何工作的
· 为什么PostgreSQL不自动缓存执行计划?
· 从被喷“假开源”到登顶 GitHub 热榜,这个开源项目上演王者归来!
· Stack Overflow,轰然倒下!
· Cursor 1.2重磅更新,这个痛点终于被解决了!
· 上周热点回顾(6.30-7.6)
· .NET AI 模板