ajax请求的五个步骤和用法_fetch可数据流分块处理
fetch是xmlHttprequest的替代品
参考:https://blog.csdn.net/TroyeSivanlp/article/details/123271225
参考:https://blog.csdn.net/TroyeSivanlp/article/details/123271225
fetch
通过数据流(Stream 对象)处理数据,可以分块读取,有利于提高网站性能表现
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,是一种异步交互方式,可以局部更新
多次请求
$.when().done(function(){}).fail(function(){})
$.when(
$.getJSON("url",function(a,status){}),$.getJSON("url",function(){})
).done(function(a,b){})
.fail(function(){})
定义:异步的JavaScript xml,能够使页面局部刷新
ajax请求的五个步骤
第一步: 创建xmlHttprequest对象 第二步:使用对象的open()和send()方法发送资源给服务器 第三步:使用对象的responseText或responseXML 属性获取服务器的响应 第四步:注册事件 onreadystatechange 状态改变就会调用 第五步:根据判断进行响应的处理
代码如下:
//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的使用
$.ajax({
url:"",
dataType:"json", //dataType
type:"get",
data:{},
async:true, //为异步
//成功或失败
success:function(res){ },
error:function(){err},
});

浙公网安备 33010602011771号