• JS高程3:Ajax与Comet-XMLHttpRequest对象


    XHR 的用法

    XHR对象,即XMLHttpRequest对象,下面看看他常见的属性和方法。

    open()方法

    它接受 3 个参数:要发送的请求的类型("get""post"等)、请求的 URL 和表示是否异步发送请求的布尔值。

    xhr.open("get", "example.php", false);
    

     需要说明两点:

    一是 URL相对于执行代码的当前页面(当然也可以使用绝对路径);

    二是调用 open()方法并不会真正发送请求,而只是启动一个请求以备发送。

    注意:

    只能向同一个域中使用相同端口和协议的 URL 发送请求。如果 URL 与启动请求的页面有任何差别,都会引发安全错误。
    send()方法

    send()方法接收一个参数,即要作为请求主体发送的数据。如果不需要通过请求主体发送
    数据,则必须传入 null,因为这个参数对有些浏览器来说是必需的。

    属性

     responseText:作为响应主体被返回的文本。
     responseXML:如果响应的内容类型是"text/xml"或"application/xml",这个属性中将保
    存包含着响应数据的 XML DOM 文档。
     status:响应的 HTTP 状态。
     statusText: HTTP 状态的说明。

    XHR 对象的 readyState 属性,该属性表示请求响应过程的当前活动阶段。这个属性可取的值如下

     0:未初始化。尚未调用 open()方法。
     1:启动。已经调用 open()方法,但尚未调用 send()方法。
     2:发送。已经调用 send()方法,但尚未接收到响应。
     3:接收。已经接收到部分响应数据。
     4:完成。已经接收到全部响应数据,而且已经可以在客户端使用了。

    必须在调用 open()之前指定 onreadystatechange事件处理程序才能确保跨浏览器兼容性。

    var xhr = createXHR();
    xhr.onreadystatechange = function(){
    	if (xhr.readyState == 4){
    		if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
    			alert(xhr.responseText);
    	} else {
    		alert("Request was unsuccessful: " + xhr.status);
    	}
    	}
    };
    xhr.open("get", "example.txt", true);
    xhr.send(null);
    

     另外,在接收到响应之前还可以调用 abort()方法来取消异步请求,如下所示:

    xhr.abort();
    

    HTTP头部信息

    请求头部信息

     Accept:浏览器能够处理的内容类型。
     Accept-Charset:浏览器能够显示的字符集。
     Accept-Encoding:浏览器能够处理的压缩编码。
     Accept-Language:浏览器当前设置的语言。
     Connection:浏览器与服务器之间连接的类型。
     Cookie:当前页面设置的任何 Cookie。
     Host:发出请求的页面所在的域 。
     Referer:发出请求的页面的 URI。注意, HTTP 规范将这个头部字段拼写错了,而为保证与规
    范一致,也只能将错就错了。(这个英文单词的正确拼法应该是 referrer。)
     User-Agent:浏览器的用户代理字符串。

    头部信息可以自定义,使用setRequestHeader()方法,需要在request发送之前进行添加

    var xhr = createXHR();
    xhr.onreadystatechange = function(){
    	if (xhr.readyState == 4){
    		if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
    			alert(xhr.responseText);
    	} else {
    		alert("Request was unsuccessful: " + xhr.status);
    	}
    	}
    };
    xhr.open("get", "example.php", true);
    xhr.setRequestHeader("MyHeader", "MyValue");
    xhr.send(null);
    

     查看响应报文的头部信息有2种方式

    查看单项

    var myHeader = xhr.getResponseHeader("MyHeader");
    

     查看所有

    var allHeaders = xhr.getAllResponseHeaders();
    

     通常的响应信息

    Date: Sun, 14 Nov 2004 18:04:03 GMT
    Server: Apache/1.3.29 (Unix)
    Vary: Accept
    X-Powered-By: PHP/4.3.8
    Connection: close
    Content-Type: text/html; charset=iso-8859-1

    GET请求

    GET请求是最常见的HTTP请求方法,用来向服务器获取信息。

    为了定向的获取信息,经常会用到查询字符串(查询字符串在URL中,以和号&隔开的键值对)

    xhr.open("get", "example.php?name1=value1&name2=value2", true);
    

     需要注意的是,查询字符串在加入到URL之前,要正确的进行编码

    function addURLParam(url, name, value) {
    	url += (url.indexOf("?") == -1 ? "?" : "&");
    	url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
    	return url;
    }
    

     这个 addURLParam()函数接受三个参数:要添加参数的 URL、参数的名称和参数的值。

    var url = "example.php";
    //添加参数
    url = addURLParam(url, "name", "Nicholas");
    url = addURLParam(url, "book", "Professional JavaScript");
    //初始化请求
    xhr.open("get", url, false);
    

    拓展:

    indexof()方法

    stringObject.indexOf(searchvalue,fromindex)
    参数描述
    searchvalue 必需。规定需检索的字符串值。
    fromindex 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。

    注意:如果没有找到查询字符串,返回-1。

    POST请求

    使用频率仅次于 GET 的是 POST 请求,通常用于向服务器发送应该被保存的数据。

    使用send()方法传入POST的数据

    模仿表单发送

    function submitData(){
    var xhr = createXHR();
    xhr.onreadystatechange = function(){
    	if (xhr.readyState == 4){
    		if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
    			alert(xhr.responseText);
    	} else {
    		alert("Request was unsuccessful: " + xhr.status);
    	}
    	}
    };
    	xhr.open("post", "postexample.php", true);
    	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	var form = document.getElementById("user-info");
    	xhr.send(serialize(form));
    }
    

    XMLHttpRequest 2级

    使用FormData()构造函数来序列化表单数据

    var xhr = createXHR();
    xhr.onreadystatechange = function(){
    	if (xhr.readyState == 4){
    		if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
    			alert(xhr.responseText);
    	} else {
    		alert("Request was unsuccessful: " + xhr.status);
    	}
    	}
    };
    xhr.open("post","postexample.php", true);
    var form = document.getElementById("user-info");
    xhr.send(new FormData(form));
    

     超时设置

    XHR有个timeout属性,如果超过时间就取消报文。

    var xhr = createXHR();
    xhr.onreadystatechange = function(){
    	if (xhr.readyState == 4){
    		try {
    			if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
    				alert(xhr.responseText);
    			} else {
    				alert("Request was unsuccessful: " + xhr.status);
    			}
    		} catch (ex){
    			//假设由 ontimeout 事件处理程序处理
    		}
    	}
    };
    xhr.open("get", "timeout.php", true);
    xhr.timeout = 1000; //将超时设置为 1 秒钟(仅适用于 IE8+)
    xhr.ontimeout = function(){
    alert("Request did not return in a second.");
    };
    xhr.send(null);
    

     目前支持超时设置的浏览器并不多。

    overrideMimeType()方法

    Firefox 最早引入了 overrideMimeType()方法,用于重写 XHR 响应的 MIME 类型。
    返回响应的 MIME 类型决定了 XHR 对象如何处理它 。

    var xhr = createXHR();
    xhr.open("get", "text.php", true);
    xhr.overrideMimeType("text/xml");
    xhr.send(null);
    
  • 相关阅读:
    String的几种初始化方法的区别
    Java编程思想之字符串
    树图 广度优先算法和深度优先算法
    bzoj1047: [HAOI2007]理想的正方形
    bzoj3124: [Sdoi2013]直径
    bzoj3930: [CQOI2015]选数
    bzoj1222: [HNOI2001]产品加工
    bzoj3578: GTY的人类基因组计划2
    bzoj4444: [Scoi2015]国旗计划
    bzoj1040: [ZJOI2008]骑士
  • 原文地址:https://www.cnblogs.com/leomei91/p/7573784.html
Copyright © 2020-2023  润新知