In front of the word

The types of response subjects we receive can be in many forms , Including strings String、ArrayBuffer object 、 Binary system Blob object 、JSON object 、javascirpt Documentation and presentation XML Document Document Object etc. . The following will focus on different subject types , Decoding the corresponding response

attribute

Before introducing response decoding , Understand first XHR object Properties of . In a general way , If the accepted data is a string , Use responseText that will do , This is also the most common attribute used to receive data . But if you get other types of data , Use responseText Maybe not

【responseText】

responseText Property returns the string received from the server , The property is read-only . If the request is unsuccessful or the data is incomplete , The attribute will be equal to null.

If the data format returned by the server is JSON、 character string 、javascript or XML, You can use responseText attribute

【response】

response Property is read-only , Return the received data body . It can be of the type ArrayBuffer、Blob、Document、JSON object 、 Or a string , This is due to XMLHttpRequest.responseType The value of the property determines

If the request is unsuccessful or the data is incomplete , The attribute will be equal to null

[ Be careful ]IE9- Browser does not support

【responseType】

responseType Property is used to specify that the server returns data (xhr.response) The type of

“”: character string ( The default value is )
“arraybuffer”:ArrayBuffer object
“blob”:Blob object
“document”:Document object
“json”:JSON object
“text”: character string

【responseXML】

responseXML Property returns the... Received from the server Document object , The property is read-only . If this request is unsuccessful , Or the data is incomplete , Or it can't be interpreted as XML or HTML, This property is equal to null

【overrideMimeType()】

This method is used to specify the data returned by the server MIME type . The method must be in send() Previous call

Traditionally , If you want to retrieve binary data from the server , We need to use this method , Artificially disguise data type as text data

however , This method is troublesome , stay XMLHttpRequest After the version upgrade , It is generally used to specify responseType Methods

character string

If the server returns a string , Direct use responseText Attribute parsing is enough

About ajax() Encapsulation of functions , Already in Last blog I have described in detail in , No more details here . Call directly ajax.js Use

<button id="btn"> Get a response </button>
<div id="result"></div>
<script>
btn.onclick = function(){
ajax({
url:'p1.php',
callback:function(data){
result.innerHTML = data;
}
})
}
</script>
<?php
// Set page content html The encoding format is utf-8, The content is plain text
header("Content-Type:text/plain;charset=utf-8");
echo ' Hello , The world ';
?>

JSON

Use ajax The most common mode of transmission is to use JSON character string , Use it directly responseText Attribute parsing is enough

<button id="btn"> Get a response </button>
<div id="result"></div>
<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+= '<div>' + obj[i].title + ':' + obj[i].data + '</div>';
}
result.innerHTML = html;
html = null;
}
})
}
</script>
<?php
header("Content-Type:application/json;charset=utf-8");
$arr = [['title'=>' Color ','data'=>' Red '],['title'=>' Size ','data'=>' Inch '],['title'=>' weight ','data'=>' kg ']];
echo json_encode($arr);
?>

XML

XML stay JSON Before appearance , Is a common data transmission format on the network , But because of its cumbersome format , So it's less used

receive XML When the document , Use responseXML To parse the data

<button id="btn"> Get a response </button>
<div id="result"></div>
<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 += '<div> Record :' + obj[i].getElementsByTagName('TITLE')[0].innerHTML + '; singer :' + obj[i].getElementsByTagName('ARTIST')[0].innerHTML + '</div>';
}
result.innerHTML = html;
html = null;
}
})
}
function ajax(obj){
//method by ajax Method of submission , The default is 'get' Method
obj.method = obj.method || 'get';
// establish xhr object
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
// Asynchronous accept response
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
//callback Is the callback function , If not set, there is no callback
obj.callback && obj.callback(xhr.responseXML);
}
}
}
// Create a data string , Used to save data to be submitted
var strData = '';
obj.data = true;
if(obj.method == 'post'){
for(var key in obj.data){
strData += '&' + key + "=" + obj.data[key];
}
// Get rid of the excess '&'
strData = strData.substring(1);
xhr.open('post',obj.url,true);
// Set request header
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
// Send a request
xhr.send(strData);
}else{
// If it is get The way , Then the characters are edited
for(var key in obj.data){
strData += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]);
}
// Get rid of the excess '&', And add random numbers , Prevent caching
strData = strData.substring(1) + '&'+Number(new Date());
xhr.open('get',obj.url+'?'+strData,true);
// Send a request
xhr.send();
}
}
</script>
<CATALOG data-livestyle-extension="available">
<CD>
<TITLE> rosemary </TITLE>
<ARTIST> Jay Chou </ARTIST>
</CD>
<CD>
<TITLE> Chengdu </TITLE>
<ARTIST> Zhao Lei </ARTIST>
</CD>
<CD>
<TITLE> It is time to </TITLE>
<ARTIST> Stefanie Sun </ARTIST>
</CD>
</CATALOG>

js

Use ajax You can also receive js file . Still use responseText To receive data , But to use eval() To execute the code

<button id="btn"> Get a response </button>
<div id="result"></div>
<script>
btn.onclick = function(){
ajax({
url:'p4.js',
callback:function(data){
eval(data);
var html = '';
for(var key in obj){
html += '<div>' + key + ':' + obj[key] + '</div>';
}
result.innerHTML = html;
html = null;
}
})
}
</script>
var obj = {
' full name ':' Little match ',
' Age ':28,
' Gender ':' male '
}

blob

stay javascript in ,Blob It usually represents binary data . But in reality Web Application ,Blob It's more about uploading and downloading pictures in binary form , Although it can realize the binary transmission of almost any file

Use ajax receive blob data , Need to use response To receive , And will responseType Set to 'blob'

[ Be careful ] To be fully compatible IE10+ browser , Need to put xhr.responseType Set in the xhr.open() and xhr.send() Between methods

<button id="btn"> Get a response </button>
<div id="result"></div>
<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 by ajax Method of submission , The default is 'get' Method
obj.method = obj.method || 'get';
// establish xhr object
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
// Asynchronous accept response
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
//callback Is the callback function , If not set, there is no callback
obj.callback && obj.callback(xhr.response);
}
}
}
// Create a data string , Used to save data to be submitted
var strData = '';
obj.data = true;
if(obj.method == 'post'){
for(var key in obj.data){
strData += '&' + key + "=" + obj.data[key];
}
// Get rid of the excess '&'
strData = strData.substring(1);
xhr.open('post',obj.url,true);
xhr.responseType = 'blob';
// Set request header
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
// Send a request
xhr.send(strData);
}else{
// If it is get The way , Then the characters are edited
for(var key in obj.data){
strData += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]);
}
// Get rid of the excess '&', And add random numbers , Prevent caching
strData = strData.substring(1) + '&'+Number(new Date());
xhr.open('get',obj.url+'?'+strData,true);
xhr.responseType = 'blob';
// Send a request
xhr.send();
}
}
</script>

arraybuffer

arraybuffer Represents a section of memory that stores binary data , and blob Is used to represent binary data . adopt ajax receive arraybuffer, Then convert it to blob data , So as to carry out further operation

responseType Set to arraybuffer, And then response As new Blob() The arguments of the constructor are passed , Generate blob object

<button id="btn"> Get a response </button>
<div id="result"></div>
<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 by ajax Method of submission , The default is 'get' Method
obj.method = obj.method || 'get';
// establish xhr object
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
// Asynchronous accept response
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
//callback Is the callback function , If not set, there is no callback
obj.callback && obj.callback(xhr.response);
}
}
}
// Create a data string , Used to save data to be submitted
var strData = '';
obj.data = true;
if(obj.method == 'post'){
for(var key in obj.data){
strData += '&' + key + "=" + obj.data[key];
}
// Get rid of the excess '&'
strData = strData.substring(1);
xhr.open('post',obj.url,true);
// Set request header
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.responseType = 'arraybuffer';
// Send a request
xhr.send(strData);
}else{
// If it is get The way , Then the characters are edited
for(var key in obj.data){
strData += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]);
}
// Get rid of the excess '&', And add random numbers , Prevent caching
strData = strData.substring(1) + '&'+Number(new Date());
xhr.open('get',obj.url+'?'+strData,true);
xhr.responseType = 'arraybuffer';
// Send a request
xhr.send();
}
}
</script>

In depth understanding of ajax Part three of the series —— More articles on response decoding

  1. In depth understanding of ajax Part three of the series

    In front of the word The types of response subjects we receive can be in many forms , Including strings String.ArrayBuffer object . Binary system Blob object .JSON object .javascirpt Documentation and presentation XML Document Document object ...

  2. In depth understanding of ajax Part three of the series —— Header information

    In front of the word Every HTTP Both the request and the response carry the corresponding header information , Some of them are useful to developers .XHR Object provides a way to manipulate header information . This article will introduce in detail HTTP The head information of Default message By default , Sending XHR At the same time of request , Will ...

  3. In depth understanding of ajax Chapter 8 of the series —— Form submission

    In front of the word In the past , The main way for users of the website to interact with the back end is through HTML Use of forms . The introduction of forms is in 1993 year , Because of its simplicity and ease of use , Until the advent of e-commerce has always maintained an important position . Understand form submission , For a deeper understanding of ajax yes ...

  4. In depth understanding of ajax Chapter 8 of the series

    In front of the word In the past , The main way for users of the website to interact with the back end is through HTML Use of forms . The introduction of forms is in 1993 year , Because of its simplicity and ease of use , Until the advent of e-commerce has always maintained an important position . Understand form submission , For a deeper understanding of ajax yes ...

  5. In depth understanding of ajax Part four of the series —— Request instance

    In front of the word In the use of ajax In the process of , The common way to request is GET and POST Two kinds of . This article will explain these two request methods in detail in the form of examples GET GET Is the most common type of request , Most commonly used to query the server for certain information . When necessary, , The query word can be ...

  6. In depth understanding of ajax Chapter seven of the series —— Pass on JSON

    In front of the word although ajax The full name is asynchronous javascript and XML. But it is currently used ajax Technical time , Pass on JSON Has become the de facto standard . Because compared with XML for ,JSON Simple and convenient . This article will ...

  7. In depth understanding of ajax Chapter seven of the series

    In front of the word although ajax The full name is asynchronous javascript and XML. But it is currently used ajax Technical time , Pass on JSON Has become the de facto standard . Because compared with XML for ,JSON Simple and convenient . This article will ...

  8. In depth understanding of closure Series Part 3 ——IIFE

    × Catalog [1] Realization [2] purpose In front of the word Strictly speaking ,IIFE It's not a closure , Because it doesn't satisfy the three conditions for a function to be a closure . But generally , People think that IIFE It's a closure , After all, closures have multiple definitions . This article will introduce in detail IIFE The realization and use of ...

  9. In depth understanding of ajax Part four of the series ——FormData

    In front of the word modern Web One of the functions frequently used in applications is the serialization of form data ,XMLHttpRequest 2 The level defines FormData type .FormData It facilitates serialization of forms and creation of data in the same format as forms . ...

Random recommendation

  1. ( summary )Oracle 11g Common administrative commands ( user 、 Table space 、 jurisdiction )

    1. start-up oracle database : from root Switch to oracle User access :su - oracle Get into sqlplus Environmental Science ,nolog Parameter indicates no login :sqlplus /nolog Log in as Administrator :sqlpl ...

  2. iOS Rich text

    background : A few days ago, I suddenly wanted to make a notebook function , In limine , I think it's very simple , One UITextView, Network caching is not working , Direct local NSUserDefault Storage , And then it's done , Art Designer , Make some nice pictures , Add a few animations , That's it ...

  3. Unix/Linux Environmental Science C Introduction to programming (19)Red Hat Entetprise Linux 7.0 Environment building

    An architecture , Including Intel X-86_64.Power and s390. The dynamic timing capability will reduce the number of interrupts inside the kernel ,Open vSwitch 2.0 The function can adjust the flow between virtual machines .RHEL 7 The default file system in is XFS, Contains a ...

  4. Wpf Modification of mouse style in , Action point modification

    lately , Making a mouse style for a control ,Ps Add a plug-in , You can edit to generate .cur Format icons . But , After all the changes , Debugging operation , It turns out that the action point of your icons is always in the upper left corner , Not in " Hand shape " The index finger of the icon ...

  5. H5 Read local file operation

    H5 Read local file operation In this paper, from : turn :http://hushicai.com/2014/03/29/html5-du-qu-ben-di-wen-jian.html Thank God for sharing . Common languages such as php. ...

  6. JS Bar code plug-in --JsBarcode Used in small programs

    Use in small programs : utils Under the folder  barcode.js Glue the following code var CHAR_TILDE = 126 var CODE_FNC1 = 102 var SET_STARTA = 103 ...

  7. [nodemon] clean exit - waiting for changes before restart

    The above log information appears , The program can't go down . reason :node When the program is initialized, it will report an error , carefully debug Well ...

  8. TensorFlow Study notes --[compute_gradients and apply_gradients Principle analysis ]

    I optimizer.minimize(loss, var_list) We all know ,TensorFlow Provides us with a wealth of optimization functions , for example GradientDescentOptimizer. This method will come from ...

  9. SQLServer Window function ( Reprint )

    One . The function of window function Window functions operate on a set of values , No need to use GROUP BY Clause to group data , You can also return both the columns of the base row and the aggregate columns in the same row . Window function , The queries for both base and aggregate columns are very simple . Two . Grammar format window ...

  10. WCF Develop the series 3 of actual combat : Self operation WCF service

    WCF Develop the series 3 of actual combat : Self operation WCF service ( original : Home of the grey bug  http://hi.baidu.com/grayworm) In the last article, we built a WCF Service site , by WCF The service library provides WEB Support , We put ...