ajax初探
在看了一些文章之后,对Ajax有了初步的一些了解。Ajax的定义不用多说,主要记录一下Ajax的简单实现。 open()方法是创建一个请求
一般默认使用的是异步请求。同步请求的时候会出现一些限制: xhr.timeout = 0; xhr.withCredentails = false; xhr.responseType = ""; 不满足以上任意一个限制,就会抛出错误。 xhr.timeout 设置请求超时时间,如果值为0,说明不限时,在这样的情况下,如果服务器一直没有响应,会出现页面堵塞的情况,会影响用户的其它交互。所以应该尽量避免使用同步请求。 xhr.withCredentails 跨域请求设置 默认值为false。跨域请求的时候需要手动设置为true。所以在同步请求的情况下,是无法进行跨域的。 xhr.responseType 设置请求返回的数据格式 这个属性是在xhr标准2中才有的,在标准1里面提供的是 overrideMimeType()方法。 除了上面提到的xhr.response,xhr提供了另外2种属性来获取请求返回的数据:xhr.responseText;xhr.responseXML。
send()方法是发送数据 try{ xhr,send(data); }catch(e){ //... }; 请求发送之后还要处理请求返回的数据,可以调用onload()方法或者onreadystatechange()方法。readyState这个属性可以追踪Ajax请求的当前状态,这个属性是可读属性,总共有5种不同的值(0-4),分别对应xhr的不同阶段,如3表示LOADING(正在下载响应体)。每次xhr.readyState的值发生变化的时候,都会触发xhr.onreadystatechange()事件。 完整例子如下: var xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.open('GET','https://cnodejs.org/api/v1/topics',true); xhr.onload = function () { //如果请求成功 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { var res = this.response; console.log(res); //do successCallback } } xhr.send(); 第二种方式是通过fetch来发送Ajax请求
默认情况下,fetch不会从服务端发送或接收任何cookies。 fetch('https://cnodejs.org/api/v1/topics',{ method: 'GET',credentials: 'include',}) .then((res)=>{ return res.json() }) .then((res)=>{ console.log(res); }) 完整例子如下: fetch('https://cnodejs.org/api/v1/topics',headers: new Headers({ 'Accept': 'application/json' }) }) .then((res)=>{ return res.json() }) .then((res)=>{ console.log(res); }) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |