ajax请求的五个步骤和用法_fetch可数据流分块处理
fetch是xmlHttprequest的替代品
参考:https://blog.csdn.net/TroyeSivanlp/article/details/123271225
参考:https://blog.csdn.net/TroyeSivanlp/article/details/123271225
fetch
通过数据流(Stream 对象)处理数据,可以分块读取,有利于提高网站性能表现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | const response = await fetch(url, { method: 'POST' , headers: { "Content-type" : "application/x-www-form-urlencoded; charset=UTF-8" , }, body: 'foo=bar&lorem=ipsum' , }); const json = await response.json(); ----------------------------------------------------------------- const user = { name: 'John' , surname: 'Smith' }; const response = await fetch( '/article/fetch/post/user' , { method: 'POST' , headers: { 'Content-Type' : 'application/json;charset=utf-8' }, body: JSON.stringify(user) //body:new DataForm() }); |
ajax
即异步的javascript和xml,是一种异步交互方式,可以局部更新
多次请求
1 2 3 4 5 6 7 | $.when().done( function (){}).fail( function (){}) $.when( $.getJSON( "url" , function (a,status){}),$.getJSON( "url" , function (){}) ).done( function (a,b){}) .fail( function (){}) |
定义:异步的JavaScript xml,能够使页面局部刷新
ajax请求的五个步骤
1 2 3 4 5 | 第一步: 创建xmlHttprequest对象 第二步:使用对象的open()和send()方法发送资源给服务器 第三步:使用对象的responseText或responseXML 属性获取服务器的响应 第四步:注册事件 onreadystatechange 状态改变就会调用 第五步:根据判断进行响应的处理 |
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | //1 创建对象 var xhr; if (window.xhr){ var xhr= new XMLHttpRequest(); } else { //针对IE5或IE6 xhr= new ActiveXObject( "Microsoft.XMLHttp" ); } //2 发送请求给服务器 xhr.open( "post" , "/url" ); 或 xhr.open( "get" , "url?name=123" ); 若是post方法: xhr.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded" ); //且 xhr.send("name="+name)发送参数 //3 接受请求 var res=xhr.requestText或xhr.requestXML属性获得服务器资源 //4 判断状态 xhr.onreadystatechange = function () { if (xhr.readyState==4 && xhr.status==200) { //5 根据状态做响应的处理 } } |
ajax的使用
1 2 3 4 5 6 7 8 9 | $.ajax({ url: "" , dataType: "json" , //dataType type: "get" , data:{}, async: true , //为异步<br>//成功或失败 success: function (res){ }, error: function (){err}, }); |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?