Table of Contents
Previous words
Attributes" >Attributes
If the result returned by the server is a string, it can be parsed directly using the responseText attribute
The most common transmission method using ajax is to use JSON characters String, you can parse it directly using the responseText attribute
Before JSON appeared, XML was the network A commonly used data transmission format, but because its format is cumbersome, it is rarely used
Use ajax to receive js files. Still use responseText to receive data, but use eval() to execute the code
In JavaScript, Blob usually represents binary data. But in actual Web
arraybuffer
Home Web Front-end JS Tutorial ajax response decoding

ajax response decoding

Mar 12, 2017 pm 03:34 PM

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”:字符串
Copy after login

[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 type

Disguised 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>
Copy after login

<?php    //设置页面内容的html编码格式是utf-8,内容是纯文本
    header("Content-Type:text/plain;charset=utf-8");    
    echo &#39;你好,世界&#39;;?>
Copy after login

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+= &#39;<p>' + obj[i].title + ':' + obj[i].data + '</p>';
            }
            result.innerHTML = html;
            html = null;
        }
    })
}</script>
Copy after login

<?php    header("Content-Type:application/json;charset=utf-8");    
    $arr = [[&#39;title&#39;=>'颜色','data'=>'红色'],['title'=>'尺寸','data'=>'英寸'],['title'=>'重量','data'=>'公斤']];    echo json_encode($arr);?>
Copy after login

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 += &#39;<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>
Copy after login

<CATALOG data-livestyle-extension="available"><CD>
    <TITLE>迷迭香</TITLE>
    <ARTIST>周杰伦</ARTIST></CD><CD>
    <TITLE>成都</TITLE>
    <ARTIST>赵雷</ARTIST></CD><CD>
    <TITLE>是时候</TITLE>
    <ARTIST>孙燕姿</ARTIST></CD></CATALOG>
Copy after login

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>
Copy after login

var obj = {    '姓名':'小火柴',    '年龄':28,    '性别':'男'}
Copy after login

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>
Copy after login

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>
Copy after login

 



The above is the detailed content of ajax response decoding. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

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.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

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

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

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 jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

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

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

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:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

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.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

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.

What are the ajax versions? What are the ajax versions? Nov 22, 2023 pm 02:00 PM

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.

See all articles