ajax基本用法
异步传输基于字符,同步传输基于比特。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
26
27
28
29
30
31
32
33
34
35
36
37
38
39// 封装一个源生的ajax函数
var eg = {};
eg.AJAX = function(config, callback){
    var xhr;
    if(window.XMLHttpRequest){ // 浏览器支持XMLHttpRequest
        xhr = new XMLHttpRequest(); // IE7+支持
    } else if(window.ActiveXObject){ // IE7以下
        try{ // 尝试创建一个低版本对象
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e){
            try { // 尝试创建一个高版本对象
                xhr = new ActiveXObject("msxml2.XMLHTTP");
            }
            catch(x){}
        }
    }
    if(xhr){ // 创建成功
        if(config.ISASYN){ // 配置为异步
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4){ // http请求成功
                    // 304 表示请求的资源并没有被修改,可以直接使用浏览器的缓存版本,响应有效
                    if((xhr.status >= 200 && xhr.status <300) || xhr.status == 304){
                        // 将服务器响应的数据传给回调函数
                        callback(xhr.responseText,xhr.responseXML); 
                    }
                }
            };
            // 在调用open之前指定onreadystatechange,确保跨浏览器兼容性
            xhr.open(config.TYPE,config.URL,true); // 启动一个请求以备发送
            xhr.send(config.DATA); // 发送异步ajax请求 ,不需要发送数据,必须传入null
        }else{
            xhr.open(config.TYPE,config.URL,false);
            xhr.send(config.DATA); // 发送同步ajax请求
            callback(xhr.responseText,xhr.responseXML);
           
        }
    }
}
readyState的值:
- 0:未初始化,未调用open
 - 1:启动,已调用open,未调用send
 - 2:请求已接收,已调用send,未收到响应
 - 3:请求已完成,且响应已就绪
 
为了避免得到缓存结果,可以在url后添加一个随机数作为标识1
URL:'content/url?t=' + Math.random();
如果想要发送自定义的请求头信息,须在open后,send前。open->setRequestHeader->send
获取响应头信息:getResponseHeader(‘字段名称’),获取全部响应头信息:getAllResponseHeaders()
GET请求
使用get常发生的一个错误:查询字符串的格式问题,查询字符串中每个参数的名称和值使用encodeURIComponent()进行编码,然后放到URL的末尾1
2
3
4
5
6function addURLParam(url,name,value){
    // 先确认是否已有参数存在
    url += (url.indexOf('?') == -1 ? '?' : '&');
    url += encodeURIComponent(name) + '+' + encodeURIComponent(value);
    return url;
}
POST请求
表单提交时内容类型:’application/x-www-form-urlencoded’。
post消耗的资源比get更多,性能方面,get的速度最多可达到post的两倍。