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删除|
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 还在手写JSON调教大模型?.NET 9有新玩法
· 复杂业务系统线上问题排查过程
· 通过抓包,深入揭秘MCP协议底层通信
· 记一次.NET MAUI项目中绑定Android库实现硬件控制的开发经历
· 糊涂啊!这个需求居然没想到用时间轮来解决
· Coze Studio:字节跳动 Coze 的开源版本来了!第一时间深度解析
· 一款超级经典复古的 Windows 9x 主题风格 Avalonia UI 控件库,满满的回忆杀!
· 我给 AI 接上了一个 C# 运行器,结果它学会了自己上网、调试代码
· 源码浅析:SpringBoot main方法结束为什么程序不停止
· Qwen Code与Claude Coder Router体验