//XHR对象的创建
//适用于IE7之前的版本
function createIeXHR() {
    if(typeof arguments.callee.activeXString != 'string') {
        var versions = ['MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.3.0', 'MSXML.XMLHttp'];
        for(var i=0, len=versons.length; i<len; i++) {
            try {
                var xhr = new ActiveXObject(versions[i]);
                arguments.callee.activeXString = versions[i];
                return xhr;
            } catch(e) {
                //
            }
        }
    }
    return new ActiveXObject(arguments.callee.activeXString);
}
//IE7+,ff,ch,sa,op
var xhr = new XMLHttpRequest();
//兼容的实现方式
function createXHR() {
    if(typeof XMLHttpRequest != 'undefined') {
        return new XMLHttpRequest();
    } else if(typeof ActiveXObject != 'undefined') {
        if(typeof arguments.callee.activeXString != 'string') {
            var versions = ['MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.3.0', 'MSXML.XMLHttp'];
            for(var i=0, len=versons.length; i<len; i++) {
                try {
                    var xhr = new ActiveXObject(versions[i]);
                    arguments.callee.activeXString = versions[i];
                    return xhr;
                } catch(e) {
                    //
                }
            }
        }
        return new ActiveXObject(arguments.callee.activeXString);
    } else {
        throw new Error('No XHR object available!');
    }
}
var xhr = createXHR();
xhr.open('post', 'test.php', false);//false表示发送同步请求
xhr.open('post', 'test.php', true);//true表示发送异步请求
xhr.send(null);//发送请求
//检测status属性以确定响应已经返回
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
    alert(xhr.statusText);
} else {
    alert("Request was unsuccessful: " + xhr.statusText);
}
//检测readyState属性,表示请求/响应过程中的当前活动阶段
var xhr = createXHR();
xhr.onreadystatechange = function() {
    if(xhr.readyState == 4) {
        if((xhr.status >= 200 && xhr.statue < 300) || xhr.status == 304) {
            alert(xhr.responseText);
        } else {
            alert("Request was unsuccessful: " + xhr.statusText);
        }
    }
};
xhr.open('get', 'test.php', true);
xhr.send(null);
//HTTP头部信息
xhr.setRequestHeader('myHeader', 'myValue');//设置自定义的请求头部信息,应该在open()之前,send()时之后
var myHeader = xhr.getResponseHeader('myHeader');//传入头部字段名,取得相应的响应头部信息
var allHeader = xhr.getAllResponseHeaders();//取得一个包含所有头部信息的长字符串
xhr.open('get', 'test.php?name1=value1 & name2=value2', true);//get方法
function addURLParam(url, name, value) {
    url += (url.indexOf('?') == -1) ? '?' : ' & ';
    url += encodeURIComponent(name) + '=' + encodeURIComponent(value);//get方法要求对传入的url进行序列化
    return url;
};
var xhr = createXHR();
xhr.onreadystatechange = function() {
    try {
        if(xhr.readyState == 4) {
            if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 204) {
                alert(xhr.responseText);
            } else {
                alert('Request was unsuccessful: ' + xhr.status);
            }
        }
    } catch(e) {
        //(ie8)timeout事件处理程序处理
    }
};
xhr.open('get', 'timeout.php', true);
xhr.timeout = 1000;//IE8为XHR构造了一个tiomeout属性
xhr.ontimeout = function() {
    alert('Request did not return in a second.');
};
xhr.send(null);
var xhr = createXHR();
xhr.load = function(e) {//Firefox引入load事件
    if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 204) {
        alert(xhr.responseText);
    } else {
        alert('Request was unsuccessful: ' + xhr.status);
    }
};
//创建一个进度指示器
xhr.onprogress = function(event) {//进度事件
    var divStatus = document.getElementById('status');
    divStatus.innerHTML = 'Received ' + event.position + ' of ' + event.totalSize + ' bytes';
}
xhr.open('get', 'test.php', true);
xhr.send(null);
//跨域请求
//HDR
var xdr = new XDomainRequest();
xdr.onload = function() {
    alert(xdr.responseText);
};
xdr.onerror = function() {
    alert("An error occurred.");
};
xdr.timeout = 1000;
xdr.ontimeout = function() {
    alert("!!!");
}
xdr.open('get', url);//XDR请求都是异步的
xdr.contentType = 'application/x-www-form-urlencoded';
xdr.send(null);
xdr.contentType = 'application/x-www-form-urlencoded';//为支持post请求而加入contentType属性
xdr.send('name1=value1 & name2=value2');
//跨域XHR
//设置Access-Control-Allow-Origin头部,并指定哪个域可以访问该资源
//如:Access-Control-Allow-Origin:http://www.wrox.com
//Access-Control-Allow-Origin:* //允许所有请求访问该资源
//JSON
//JSON的表示
{
    "name" : 'chemdemo',
    'title': 'student',
    'auhtor': false,
    'age' : 23
}
[
    {
        "name" : 'chemdemo',
        'title': 'student',
        'auhtor': false,
        'age' : 23
    },
    {
        "name" : 'chemdemo',
        'title': 'student',
        'auhtor': false,
        'age' : 23
    }
]
//求值为一个数组
var people = eval(jsonText);
//访问数据
alert(people[0].name);
//如果自己编写代码对JSON求值,最好将输入的文本放在一对圆括号中
var obj1 = eval("{}");//抛出错误
var obj2 = eval("({})");//没问题
var obj3 = eval("(" + jsonText + ")");//通用解决方案
//在AJAX中使用JSON
var jsonText = "{
    \"name\": \"chemdemo\",
    \"age\": 24,
    \"author\": false
}";
var obj = JSON.parse(jsonText, function(key, value) {//过滤JSON数据
    switch(key) {
        case 'age':
            return value + 1;
        case 'author':
            return undefined;
        default:
            return value;
    }
});
alert(obj.name);//chemdemo
alert(obj.age);//25
//发送AJAX请求从服务器取得数据,在客户端生成<ul/>元素
var xhr = createHXR();
xhr.onreadychange = function() {
    if(xhr.readyState == 4) {
        if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
            var contacts = JSON.parse(xhr.responseText);
            var list = document.getElementById("contacts"); 
            for(var i=0, len=contacts.length; i<len; i++) {
                var li = document.createElement('li');
                li.innerHTML = '<a href=\"mailto:' + contacts[i].email + '\">' + contacts[i].name + '</a>';
                list.appendChild(li);
            }
        }
    }
};
xhr.open('get', 'text.php', true);
xhr.send(null);
var contacts = {
    name : '',
    age : 24,
    email : 'chemdemo@foxmail.com'
};
var jsonText = JSON.stringify(contacts);//JSON对象的stringify()方法,把JSON放到post请求中
alert(jsonText);
var jsonText = JSON.stringify([new Function()], function(key, value) {
    if(value instanceof Function) {
        return '(function)';
    } else {
        return value;
    }
});
alert(jsonText);
//使用post请求将JSON文本传递给send()
var xhr = createXHR();
var contact = {
    name : 'chemdemo',
    email : 'chemdme@foxmail.com'
};
xhr.onreadystatechange = function() {
    if(xhr.readyState == 4) {
        if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
            slert(xhr.responseText);
        }
    }
};
xhr.open('post', 'addContact.php', true);
xhr.send(JSON.stringify(contact));