您好,欢迎访问一九零五行业门户网

ajax响应解码

前面的话我们接收到的响应主体类型可以是多种形式的,包括字符串string、arraybuffer对象、二进制blob对象、json对象、javascirpt文件及表示xml文档的document对象等。下面将针对不同的主体类型,进行相应的响应解码
属性在介绍响应解码之前,要先了解xhr对象的属性。一般地,如果接受的数据是字符串,使用responsetext即可,这也是最常用的用于接收数据的属性。但如果获取了其他类型的数据,使用responsetext可能就不太合适了
【responsetext】
responsetext属性返回从服务器接收到的字符串,该属性为只读。如果本次请求没有成功或者数据不完整,该属性就会等于null。
如果服务器返回的数据格式是json、字符串、javascript或xml,都可以使用responsetext属性
【response】
response属性为只读,返回接收到的数据体。它的类型可以是arraybuffer、blob、document、json对象、或者一个字符串,这由xmlhttprequest.responsetype属性的值决定
如果本次请求没有成功或者数据不完整,该属性就会等于null
[注意]ie9-浏览器不支持
【responsetype】
responsetype属性用来指定服务器返回数据(xhr.response)的类型
“”:字符串(默认值) “arraybuffer”:arraybuffer对象 “blob”:blob对象 “document”:document对象 “json”:json对象 “text”:字符串
【responsexml】
responsexml属性返回从服务器接收到的document对象,该属性为只读。如果本次请求没有成功,或者数据不完整,或者不能被解析为xml或html,该属性等于null
【overridemimetype()】
该方法用来指定服务器返回数据的mime类型。该方法必须在send()之前调用
传统上,如果希望从服务器取回二进制数据,就要使用这个方法,人为将数据类型伪装成文本数据
但是,这种方法很麻烦,在xmlhttprequest版本升级以后,一般采用指定responsetype的方法
字符串如果服务器返回的结果是一个字符串,则直接使用responsetext属性解析即可
关于ajax()函数的封装,已经在上一篇博客中详细介绍过,这里就不再赘述。直接调用ajax.js使用
<button id="btn">取得响应</button><p id="result"></p><script>btn.onclick = function(){     ajax({         url:'p1.php',         callback:function(data){             result.innerhtml = data;         }     }) }</script>
<?php //设置页面内容的html编码格式是utf-8,内容是纯文本 header("content-type:text/plain;charset=utf-8"); echo '你好,世界';?>
json使用ajax最常用的传输方式就是使用json字符串,直接使用responsetext属性解析即可
<button id="btn">取得响应</button><p id="result"></p><script>btn.onclick = function(){     ajax({         url:'p2.php',         callback:function(data){            var obj = json.parse(data);            var html = '';            for(var i = 0; i < obj.length; i++){ html+= '<p>' + obj[i].title + ':' + obj[i].data + '</p>';             }             result.innerhtml = html;             html = null;         }     }) }</script>
<?php header("content-type:application/json;charset=utf-8"); $arr = [['title'=>'颜色','data'=>'红色'],['title'=>'尺寸','data'=>'英寸'],['title'=>'重量','data'=>'公斤']];    echo json_encode($arr);?>
xmlxml在json出现之前,是网络上常用的数据传输格式,但由于其格式较笨重,所以用的较少
接收xml文档时,使用responsexml来对数据进行解析
<button id="btn">取得响应</button><p id="result"></p><script>btn.onclick = function(){     ajax({         url:'p3.xml',         callback:function(data){           var obj = data.getelementsbytagname('cd');           var html = '';           for(var i = 0; i < obj.length; i++){ html += '<p>唱片:' + obj[i].getelementsbytagname('title')[0].innerhtml + ';歌手:' + obj[i].getelementsbytagname('artist')[0].innerhtml  + '</p>';            }            result.innerhtml = html;            html = null;         }     }) }function ajax(obj){    //method为ajax提交的方式,默认为'get'方法    obj.method = obj.method || 'get';    //创建xhr对象     var xhr;    if(window.xmlhttprequest){         xhr = new xmlhttprequest();     }else{         xhr = new activexobject('microsoft.xmlhttp');     }    //异步接受响应    xhr.onreadystatechange = function(){        if(xhr.readystate == 4){            if(xhr.status == 200){                //callback为回调函数,如果不设置则无回调                obj.callback && obj.callback(xhr.responsexml);             }         }     }    //创建数据字符串,用来保存要提交的数据     var strdata = '';     obj.data = true;    if(obj.method == 'post'){        for(var key in obj.data){             strdata += '&' + key + = + obj.data[key];         }             //去掉多余的'&'        strdata = strdata.substring(1);          xhr.open('post',obj.url,true);        //设置请求头        xhr.setrequestheader(content-type,application/x-www-form-urlencoded);        //发送请求        xhr.send(strdata);         }else{        //如果是get方式,则对字符进行编成         for(var key in obj.data){             strdata += '&' + encodeuricomponent(key) + = + encodeuricomponent(obj.data[key]);         }             //去掉多余的'&',并增加随机数,防止缓存        strdata = strdata.substring(1) + '&'+number(new date());            xhr.open('get',obj.url+'?'+strdata,true);        //发送请求        xhr.send();         } }</script>
<catalog data-livestyle-extension="available"><cd>     <title>迷迭香</title>     <artist>周杰伦</artist></cd><cd>     <title>成都</title>     <artist>赵雷</artist></cd><cd>     <title>是时候</title>     <artist>孙燕姿</artist></cd></catalog>
js使用ajax也可以接收js文件。仍然使用responsetext来接收数据,但要使用eval()来执行代码
<button id="btn">取得响应</button><p id="result"></p><script>btn.onclick = function(){     ajax({         url:'p4.js',         callback:function(data){             eval(data);            var html = '';            for(var key in obj){                 html += '<p>' + key + ':' + obj[key] + '</p>';             }             result.innerhtml = html;             html = null;         }     }) }</script>
var obj = {    '姓名':'小火柴',    '年龄':28,    '性别':'男'}
blob在javascript中,blob通常表示二进制数据。但在实际web应用中,blob更多是图片二进制形式的上传与下载,虽然其可以实现几乎任意文件的二进制传输
使用ajax接收blob数据,需要使用response来接收,并且将responsetype设置为'blob'
[注意]要完全兼容ie10+浏览器,需要将xhr.responsetype设置在xhr.open()和xhr.send()方法之间
<button id="btn">取得响应</button><p id="result"></p><script>btn.onclick = function(){     ajax({         url:'p5.gif',         callback:function(data){            var img = document.createelement('img');             img.onload = function(){                 url.revokeobjecturl(img.src);             }             img.src = url.createobjecturl(data);            if(!result.innerhtml){                 result.appendchild(img);             }                      },         method:'post'     }) }function ajax(obj){    //method为ajax提交的方式,默认为'get'方法    obj.method = obj.method || 'get';    //创建xhr对象     var xhr;    if(window.xmlhttprequest){         xhr = new xmlhttprequest();     }else{         xhr = new activexobject('microsoft.xmlhttp');     }    //异步接受响应    xhr.onreadystatechange = function(){        if(xhr.readystate == 4){            if(xhr.status == 200){                //callback为回调函数,如果不设置则无回调                obj.callback && obj.callback(xhr.response);             }         }     }    //创建数据字符串,用来保存要提交的数据     var strdata = '';     obj.data = true;    if(obj.method == 'post'){        for(var key in obj.data){             strdata += '&' + key + = + obj.data[key];         }             //去掉多余的'&'        strdata = strdata.substring(1);          xhr.open('post',obj.url,true);         xhr.responsetype = 'blob';        //设置请求头        xhr.setrequestheader(content-type,application/x-www-form-urlencoded);        //发送请求        xhr.send(strdata);         }else{        //如果是get方式,则对字符进行编成         for(var key in obj.data){             strdata += '&' + encodeuricomponent(key) + = + encodeuricomponent(obj.data[key]);         }             //去掉多余的'&',并增加随机数,防止缓存        strdata = strdata.substring(1) + '&'+number(new date());            xhr.open('get',obj.url+'?'+strdata,true);         xhr.responsetype = 'blob';        //发送请求        xhr.send();         } }</script>
arraybufferarraybuffer代表储存二进制数据的一段内存,而blob则用于表示二进制数据。通过ajax接收arraybuffer,然后将其转换为blob数据,从而进行进一步的操作
responsetype设置为arraybuffer,然后将response作为new blob()构造函数的参数传递,生成blob对象
<button id="btn">取得响应</button><p id="result"></p><script>btn.onclick = function(){     ajax({         url:'p5.gif',         callback:function(data){            var img = document.createelement('img');             img.onload = function(){                 url.revokeobjecturl(img.src);             }             img.src = url.createobjecturl(new blob([data]));            if(!result.innerhtml){                 result.appendchild(img);             }                     }     }) }function ajax(obj){    //method为ajax提交的方式,默认为'get'方法    obj.method = obj.method || 'get';    //创建xhr对象     var xhr;    if(window.xmlhttprequest){         xhr = new xmlhttprequest();     }else{         xhr = new activexobject('microsoft.xmlhttp');     }    //异步接受响应    xhr.onreadystatechange = function(){        if(xhr.readystate == 4){            if(xhr.status == 200){                //callback为回调函数,如果不设置则无回调                obj.callback && obj.callback(xhr.response);             }         }     }    //创建数据字符串,用来保存要提交的数据     var strdata = '';     obj.data = true;    if(obj.method == 'post'){        for(var key in obj.data){             strdata += '&' + key + = + obj.data[key];         }             //去掉多余的'&'        strdata = strdata.substring(1);          xhr.open('post',obj.url,true);        //设置请求头        xhr.setrequestheader(content-type,application/x-www-form-urlencoded);         xhr.responsetype = 'arraybuffer';        //发送请求        xhr.send(strdata);         }else{        //如果是get方式,则对字符进行编成         for(var key in obj.data){             strdata += '&' + encodeuricomponent(key) + = + encodeuricomponent(obj.data[key]);         }             //去掉多余的'&',并增加随机数,防止缓存        strdata = strdata.substring(1) + '&'+number(new date());            xhr.open('get',obj.url+'?'+strdata,true);         xhr.responsetype = 'arraybuffer';        //发送请求        xhr.send();         } }</script>
以上就是ajax响应解码的详细内容。
其它类似信息

推荐信息