ajax response decoding
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 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
The most common transmission method using ajax is to use JSON characters String, you can parse it directly using the responseText attribute
<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);?>
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 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
Use ajax to receive js files. Still use responseText to receive data, but use eval() to execute the code
<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
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 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>
arraybuffer
arraybuffer代表储存二进制数据的一段内存,而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>
The above is the detailed content of ajax response decoding. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

Ajax is not a specific version, but a technology that uses a collection of technologies to asynchronously load and update web page content. Ajax does not have a specific version number, but there are some variations or extensions of ajax: 1. jQuery AJAX; 2. Axios; 3. Fetch API; 4. JSONP; 5. XMLHttpRequest Level 2; 6. WebSockets; 7. Server-Sent Events; 8, GraphQL, etc.
