Previous words
The response body type we receive can be in many forms, including StringString, ArrayBuffer Object, binary Blob object, JSON object, javascirpt file and Document object representing the XML document, etc. The following will carry out corresponding response decoding for different subject types
Attributes
Before introducing response decoding, You must first understand the properties of the XHR object. Generally, if the received data is a string, just use responseseText, which is also the most commonly used attribute for receiving data. But if other types of data are obtained, it may not be appropriate to use responseText
[responseText]
The responseText attribute returns the string received from the service server, This property is read-only. If this request is unsuccessful or the data is incomplete, this attribute will equal null.
If the data format returned by the server is JSON, string, javascript or XML, you can use the responseText attribute
[response]
response attribute It is read-only and returns the received data body. Its type can be ArrayBuffer, Blob, Document, JSON object, or a string, which is determined by the value of the XMLHttpRequest.responseType attribute
If this request is unsuccessful or the data is incomplete, this attribute will be equal to null
[Note]IE9-browser does not support
[responseType]
The responseType attribute is used to specify the type of data returned by the server (xhr.response)
“”:字符串(默认值) “arraybuffer”:ArrayBuffer对象 “blob”:Blob对象 “document”:Document对象 “json”:JSON对象 “text”:字符串
[responseXML]
The responseXML attribute returns the Document object received from the server. This attribute is read-only. If this request is unsuccessful, or the data is incomplete, or cannot be parsed as XML or HTML, this attribute is equal to null
【overrideMimeType()】
This method is used to specify the data returned by the server MIME type. This method must be called before send(). Traditionally, if you want to retrieve binary data from the server, you must use this method to artificially change the
data typeDisguised as text data However, this method is very troublesome. After the XMLHttpRequest version is upgraded, the method of specifying responseType is generally used
String
If the result returned by the server is a string, it can be parsed directly using the responseText attribute
Regarding the encapsulation of the ajax()
function, it has been introduced in detail in the previous blog, here I won’t go into details. Directly call ajax.js using
<button>取得响应</button><p></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
The most common transmission method using ajax is to use JSON characters String, you can parse it directly using the responseText attribute
<button>取得响应</button><p></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 + ''; } 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);?>
XML
Before JSON appeared, XML was the network A commonly used data transmission format, but because its format is cumbersome, it is rarely used
When receiving XML documents, use responseXML to parse the data
<button>取得响应</button><p></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 + ''; } 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><cd> <title>迷迭香</title> <artist>周杰伦</artist></cd><cd> <title>成都</title> <artist>赵雷</artist></cd><cd> <title>是时候</title> <artist>孙燕姿</artist></cd></catalog>
js
Use ajax to receive js files. Still use responseText to receive data, but use eval() to execute the code
<button>取得响应</button><p></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] + ''; } result.innerHTML = html; html = null; } }) }</script>
var obj = { '姓名':'小火柴', '年龄':28, '性别':'男'}
blob
In JavaScript, Blob usually represents binary data. But in actual Web
applications, Blob is more of a picturebinary formuploadand download, although it can achieve binary transmission of almost any file To use ajax to receive blob data, you need to use response to receive it, and set the responseType to 'blob'
[Note] To be fully compatible with IE10+ browsers, you need to set xhr.responseType in xhr.open( ) and the xhr.send() method
<button>取得响应</button><p></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>
arraybuffer
arraybuffer代表储存二进制数据的一段内存,而blob则用于表示二进制数据。通过ajax接收arraybuffer,然后将其转换为blob数据,从而进行进一步的操作
responseType设置为arraybuffer,然后将response作为new Blob()构造函数的参数传递,生成blob对象
<button>取得响应</button><p></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>
The above is the detailed content of ajax response decoding. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software