Ajax技术详解
xhr.onreadystatechange = function (){
//2xx状态与表示从缓存中直接取出的304可以看是成功的,IE(非原生的XHR对象)中会将204设置为1223,opera会在取得204时设置为0
if (xhr.readyState == 4 && ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0)){
options.callBack(converter[dataType].call(this, xhr.responseText, xhr.responseXML));
}
var request = new XMLHttpRequest();
request.open(\’POST\’, url); //对指定URL发送POST请求
request.send(JSON.stringify(data));//data对象要转换为json类型
* GET请求
* @param options 【该参数是一个object】
* {url: \’http://www.plateno.com/index.html, data: {name: \’luke\’}, callBack: function(data){}}
*/
function get(options){
var xhr = new XMLHttpRequest(),
async = options.async || true;
try{
//判断是否传参数
var data = \’\’, n = 0, a = \’\’;
if (options.data){
data = \’?\’;
for (var name in options.data){
n == 0 ? a = \’\’ : a = \’&\’;
n++;
data += a + name +\’=\’+ encodeURI(options.data[name])
}
}
//判断是否缓存
var cache = \’&\’ + new Data().getTime();
xhr.send(); //发送请求
//监听请求过程
xhr.onreadystatechange = function (){
//2xx状态与表示从缓存中直接取出的304可以看是成功的,IE(非原生的XHR对象)中会将204设置为1223,opera会在取得204时设置为0
if (xhr.readyState == 4 && ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0)){
options.callBack.call(this, xhr.responseText, xhr.responseXML);
}
* POST请求
* @param options 【该参数是一个object】
* {url: \’http://www.plateno.com/index.html\’, data:{name: \’luke\’}, callBack: function(data){}}
*/
function post(options) {
var xhr = new XMLHttpRequest(),
async = options.async || true;
try{
//判断是否传参数
var data = \’\’, n = 0, a = \’\’;
if (options.data){
for (var name in options.data){
n == 0 ? a = \’\’ : a = \’&\’;
n++;
data += a + name +\’=\’+ options.data[name]
}
}
xhr.open(\’post\’, options.url, async); //设置请求数据
xhr.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded; charset=utf-8″); //设置请求头
xhr.send(data); //发送请求
//监听请求过程
xhr.onreadystatechange = function (){
//2xx状态与表示从缓存中直接取出的304可以看是成功的,IE(非原生的XHR对象)中会将204设置为1223,opera会在取得204时设置为0
if (xhr.readyState == 4 && ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0)){
options.callBack(converter[dataType].call(this, xhr.responseText, xhr.responseXML));
}
}
}catch(e){throw new Error(\’POST请求失败\’);}