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},
});
posted @   lxq3280  阅读(416)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
点击右上角即可分享
微信分享提示