Ajax response Decoding

Source: Internet
Author: User
The response body types we receive can be in various forms, including String, ArrayBuffer, binary Blob, JSON, cirpt, and Document objects that represent XML documents. Next we will decode the response for different subject types.

The response body types we receive can be in various forms, including String, ArrayBuffer, binary Blob, JSON, cirpt, and Document objects that represent XML documents. The response Decoding for different subject types is as follows:

Attribute

Before introducing response decoding, you must first understand the properties of the XHR object. Generally, if the received data is a string, use responseText, which is also the most common attribute for receiving data. However, if other types of data are obtained, it may be inappropriate to use responseText.

[ResponseText]

The responseText property returns the string received from the server, which is read-only. If the request fails or the data is incomplete, the attribute is null.

If the data format returned by the server is JSON, String, javascript, or XML, you can use the responseText attribute.

[Response]

The response attribute is read-only and the received data body is returned. Its type can be ArrayBuffer, Blob, Document, JSON object, or a string, which is determined by the value of the XMLHttpRequest. responseType attribute.

If the request fails or the data is incomplete, this attribute is equal to null.

[Note] IE9-not supported by browsers

[ResponseType]

The responseType attribute is used to specify the type of data returned by the server (xhr. response ).


"": String (default) "arraybuffer": ArrayBuffer object "blob": Blob Object "document": Document Object "json": JSON object "text": String

[ResponseXML]

The responseXML attribute returns the Document Object received from the server, which is read-only. If the request fails, the data is incomplete, or cannot be parsed as XML or HTML, the attribute is null.

[OverrideMimeType ()]

This method is used to specify the MIME type of the data returned by the server. This method must be called before sending ().

Traditionally, if you want to retrieve binary data from the server, you must use this method to disguise the data type as text data.

However, this method is very troublesome. After the XMLHttpRequest version is upgraded, the responseType method is specified.

String

If the server returns a string, use the responseText attribute to parse it.

The encapsulation of ajax () functions has been described in detail in the previous blog. I will not go into details here. Directly call ajax. js


Get Response

Script btn. onclick = function () {ajax ({url: 'p1. php', callback: function (data) {result. innerHTML = data ;}})} script


 
JSON

The most common transmission method using ajax is to use a JSON string and directly use the responseText attribute for parsing.


Get Response

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 + ='

'+ Obj [I]. title +': '+ obj [I]. data +'

';}Result. innerHTML = html; html = null ;}})} script


 'Color', 'data' => 'red'], ['title' => 'SIZE', 'data' => 'inches], ['title' => 'weight', 'data' => 'kg ']; echo json_encode ($ arr);?>
XML

Before the emergence of JSON, XML is a commonly used data transmission format on the network. However, XML is rarely used because of its cumbersome format.

When receiving XML documents, use responseXML to parse the data


Get Response

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 + ='

Album: '+ obj [I]. getElementsByTagName ('title') [0]. innerHTML + '; ARTIST:' + obj [I]. getElementsByTagName ('artlist') [0]. innerHTML +'

';} Result. innerHTML = html; html = null ;}})} function ajax (obj) {// method: ajax submission method. The default value is 'get' method obj. method = obj. method | 'get'; // create an xhr object var xhr; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} // asynchronously accepts the response xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {// callback is the callback function. If this parameter is not set, no callback obj is returned. callback & obj. Callback (xhr. responseXML) ;}}// create a data string to save the data to be submitted var strData = ''; obj. data = true; if (obj. method = 'post') {for (var key in obj. data) {strData + = '&' + key + "=" + obj. data [key];} // remove the extra '&' strData = strData. substring (1); xhr. open ('post', obj. url, true); // set the request header xhr. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); // send the request xhr. send (strData);} else {// If the get method is used, the characters are compiled (Var key in obj. data) {strData + = '&' + encodeURIComponent (key) + "=" + encodeURIComponent (obj. data [key]);} // remove unnecessary '&' and add random numbers to prevent caching strData = strData. substring (1) + '&' + Number (new Date (); xhr. open ('get', obj. url + '? '+ StrData, true); // send the request xhr. send () ;}} script


 
      
   RosemaryJay Chou
  
      
   ChengduZhao Lei
  
      
   TimeSun Yanzi
  
 
Js

You can also use ajax to receive js files. Still use responseText to receive data, but use eval () to execute code


Get Response

Script btn. onclick = function () {ajax ({url: 'p4. js', callback: function (data) {eval (data); var html = ''; for (var key in obj) {html + ='

'+ Key +': '+ obj [key] +'

';}Result. innerHTML = html; html = null ;}})} script


Var obj = {'name': 'Little Match', 'age': 28, 'Gender ': 'male '}
Blob

In javascript, Blob usually represents binary data. However, in actual Web applications, Blob uploads and downloads images in binary format, although it can implement binary transmission of almost any file

To receive blob Data Using ajax, you must use response to receive the data and set responseType to 'blob'

[Note] to be fully compatible with IE10 + browsers, you must set xhr. responseType between xhr. open () and xhr. send () methods.


Get Response

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 is the ajax submission method. The default value is the 'get' method obj. method = obj. method | 'get'; // create an xhr object var xhr; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} // asynchronously accepts the response xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {// callback is the callback function. If not set, no callback ob J. callback & obj. callback (xhr. response) ;}}// create a data string to save the data to be submitted var strData = ''; obj. data = true; if (obj. method = 'post') {for (var key in obj. data) {strData + = '&' + key + "=" + obj. data [key];} // remove the extra '&' strData = strData. substring (1); xhr. open ('post', obj. url, true); xhr. responseType = 'blob '; // sets the request header xhr. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); // send the request xhr. send (StrData);} else {// If the get method is used, the characters are compiled into for (var key in obj. data) {strData + = '&' + encodeURIComponent (key) + "=" + encodeURIComponent (obj. data [key]);} // remove unnecessary '&' and add random numbers to prevent caching strData = strData. substring (1) + '&' + Number (new Date (); xhr. open ('get', obj. url + '? '+ StrData, true); xhr. responseType = 'blob'; // send the request xhr. send () ;}} script

Arraybuffer

Arraybuffer indicates a piece of memory for storing binary data, while blob indicates binary data. Receives arraybuffer through ajax and converts it to blob data for further operations.

Set responseType to arraybuffer, and pass response as a parameter of the new Blob () constructor to generate the blob Object.


Get Response

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 is the ajax submission method. The default value is the 'get' method obj. method = obj. method | 'get'; // create an xhr object var xhr; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} // asynchronously accepts the response xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {// callback is the callback function. If this parameter is not set, no callback obj is returned. callback & o Bj. callback (xhr. response) ;}}// create a data string to save the data to be submitted var strData = ''; obj. data = true; if (obj. method = 'post') {for (var key in obj. data) {strData + = '&' + key + "=" + obj. data [key];} // remove the extra '&' strData = strData. substring (1); xhr. open ('post', obj. url, true); // set the request header xhr. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); xhr. responseType = 'arraybuffer'; // send the request xhr. send (strData );} Else {// If the get method is used, the characters are compiled into for (var key in obj. data) {strData + = '&' + encodeURIComponent (key) + "=" + encodeURIComponent (obj. data [key]);} // remove unnecessary '&' and add random numbers to prevent caching strData = strData. substring (1) + '&' + Number (new Date (); xhr. open ('get', obj. url + '? '+ StrData, true); xhr. responseType = 'arraybuffer'; // send the request xhr. send () ;}} script

The above is the details of ajax response decoding. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.