Ajax的初步使用

Ajax的初步使用

定义(来自MDN)

(异步JavaScript和XML)Asynchronous JavaScript + XML, 其本身不是一种新技术,而是一个在 2005年被Jesse James Garrett提出的新术语,用来描述一种使用现有技术集合的‘新’方法,包括: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, 以及最重要的 XMLHttpRequest object当使用结合了这些技术的AJAX模型以后, 网页程序能够快速地将渐步更新呈现在用户界面上,不需要重载(刷新)整个页面。这使得程序能够更快地回应用户的操作。

尽管X在Ajax中代表XML, 但由于JSON的许多优势,比如更加轻量以及作为Javascript的一部分,目前JSON的使用比XML更加普遍。JSON和XML都被用于在Ajax模型中打包信息。

XMLHttpRequest对象

XMLHttpRequest对象充当着浏览器中的脚本(客户端)与服务器之间的中间人角色。JS通过这个对象可以自己发送请求,同时也自己处理响应。

XHR对象在IE中可能会遇到MSXML2.XMLHttp、MSXML2.XMLHttp.3.0、MSXML2.XMLHttp.6.0三个不同版本(IE7以前)。IE7+、Firefox、Opera、Chrome和Safari都支持原生的XHR对象,在这些;浏览器中创建XHR对象则用XMLHttpRequest构造函数。

<pre class="md-fences md-end-block" cid="n12" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Consolas, "Liberation Mono", Courier, monospace; font-size: 0.9em; white-space: pre; text-align: left; break-inside: avoid; display: block; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(221, 221, 221); border-radius: 3px; padding: 8px 1em 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;" lang="javascript" contenteditable="false">function getHTTPObject() {
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0");}
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP");}
catch (e) {}
return false;
}
return new XMLHttpRequest();
}</pre>

XHR

XHR对象第一个方法是open方法,它用来指定服务器上将要访问的文件,指定请求类型:GET、POST。

xhr.open(“get”,"example.php",false)

第一个参数是要发送的请求的类型、第二个数请求的URL、第三个请求时表示是否异步发送请求的布尔值。

<pre class="md-fences md-end-block" cid="n20" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Consolas, "Liberation Mono", Courier, monospace; font-size: 0.9em; white-space: pre; text-align: left; break-inside: avoid; display: block; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(221, 221, 221); border-radius: 3px; padding: 8px 1em 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;" lang="javascript" contenteditable="false">
function getNewContent () {
var request = getHTTPObject();
if (request) {
request.open("GET","example.txt",true);
request.onreadystatechange = function() {
if(request.readyState == 4||request.status >= 200 && request.status <300 || request.status == 304) {
var para = document.createElement("p");
var txt = document.createTextNode(request.responseText);
para.appendChild(txt);
document.getElementById('new').appendChild(para);
}
};
request.send(null);
}else {
alert('Sorry,your browser doesn`t suppor XMLHttpRequset');
}
}
addLoadEvent(getNewContent);</pre>

onreadystatechange是一个事件处理函数,他会在服务器给XHR对象送回响应的时候被处罚执行。在这个处理函数中,可以根据服务器的具体响应做相应的处理。

收到响应后,响应数据会自动填充XHR对象的属性,相关属性简介如下。

  • responseText:获得字符串形式的响应数据。

  • responseXML:获得 XML 形式的响应数据。

  • status:响应的HTTP状态。

  • sstatusText:HTTP状态的说明。

收到响应后,第一部检查status属性,已确定响应已经成功返回。一般来说,将HTTP状态代码为200作为成功响应的标志。池外,状态代码为304表示请求的资源没有被修改,可以直接使用浏览器中缓存的版本,意味着响应也是有效的。

readyState属性表示请求/响应过程中的当前活动阶段。这个属性可取的值如下

  • 0: 请求未初始化

  • 1: 服务器连接已建立

  • 2: 请求已接收

  • 3: 请求处理中

  • 4: 请求已完成,且响应已就绪

通常我们只对值为4的阶段感兴趣,这时候所有数据已经就绪。

GET请求

最常用于向服务器查询某些信息。

POST请求

通常用于向服务器发送应该被保存的数据。

Ajax的同源策略

石头XHR对象发送的请求只能访问与其所在的HTML处于同一域中的数据,不能向其他域发送请求。此外,游戏浏览器会限制Ajax请求使用的协议。例如,Chrome中,使用file://协议从自己的硬盘里加载emample.txt文件,会看到"Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.(跨域请求只支持HTTP协议)的错误消息"。

XMLHttpRequest2级

FormData

表单数据的序列化。创建FormData()对象,利用data.append()方法接受两个参数:键和值,分别对应表单字段的名字和字段中包含的值。

超时设定

timeout属性,表示请求在等待响应多少毫秒后就终止。在设置数值后,如果在规定时间内浏览器没有收到相应,就会触发timeout事件,进而调用ontimeout事件处理程序。

overrideMimeType()方法

重写XHR响应的MIME类型

进度事件

  • load事件

  • progress事件

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容