XMLHttpRequest.responseType 属性

XMLHttpRequest.responseType 属性

XMLHttpRequest 是一个 JavaScript API,允许网页开发人员向服务器发送 HTTP 请求,并在不重新加载整个页面的情况下接收响应数据。它通常用于开发动态网页应用程序,这些应用程序可以在后台从服务器检索数据,并在不干扰用户体验的情况下更新网页。

为了演示XMLHttpRequest的工作原理,我们来考虑一个例子,假设您正在构建一个显示特定位置当前天气的网站。您可以使用XMLHttpRequest API向天气API服务器发送一个请求,服务器将以一个包含天气数据的JSON对象作为响应进行返回。然后您可以使用JavaScript解析JSON文档,并在网页上显示相关的天气信息。

XMLHttpRequest.responseType 是XMLHttpRequest 对象的一个属性,用于指定服务器应该返回的响应类型。例如,假设您正在设计一个使用API检索特定区域天气数据的天气应用程序。为了在应用程序仪表盘上显示当前温度,您可以使用XMLHttpRequest对象向天气API发送一个GET请求,并将responseType属性设置为“json”,因为API以JSON对象的形式提供天气数据。

数据检索完成后,您可以使用点号符号访问JSON对象的当前温度属性,然后在您的天气应用程序的仪表盘上显示它。

语法: 以下是使用XMLHttpRequest.responseType属性的语法:

XMLHttpRequest.responseType = value;

value: 下面是可以与此属性配合使用的值及其相应的语法,以生成适当的响应。

  • 空字符串: 这是XMLHttpRequest.responseType的默认值。当响应类型设置为空字符串时,XMLHttpRequest对象的response属性将包含响应作为字符串。
  • arraybuffer: 当响应类型设置为”arraybuffer”时,XMLHttpRequest对象的response属性将包含响应作为ArrayBuffer对象。
  • blob: 当响应类型设置为”blob”时,XMLHttpRequest对象的response属性将包含响应作为Blob对象。
  • document: 当响应类型设置为”document”时,XMLHttpRequest对象的response属性将包含响应作为HTML Document对象。
  • json: 当响应类型设置为”JSON”时,XMLHttpRequest对象的response属性将包含响应作为已从JSON字符串解析的JavaScript对象。
  • text: 当响应类型设置为”text”时,XMLHttpRequest对象的response属性将包含响应作为字符串。

语法:

XMLHttpRequest.responseType = '';
XMLHttpRequest.responseType = 'arraybuffer';
XMLHttpRequest.responseType = 'blob';
XMLHttpRequest.responseType = 'document';
XMLHttpRequest.responseType = 'json';
XMLHttpRequest.responseType = 'text';

示例1: 让我们创建一个XMLHttpRequest对象并向服务器请求JSON数据。我们创建了一个名为 GeeksforGeeks.json 的文件,其中包含以下JSON对象。

{
    "courses" : [{
        "course_id":101,
        "title": "Data Structures and Algorithms",
        "description": "DSA Self Paced Course – Basic to Advanced",
        "price":1000,
        "discountPercentage": 80,
        "rating": 4.69
    },
    {
        "course_id": 102,
        "title": "Web Development",
        "description": "Full Stack Development Self Paced Course – Basic to Advanced",
        "price": 3000,
        "discountPercentage": 70,
        "rating": 4.0
    }]
}

GeeksforGeeks.json 获取响应,并更新我们在 index.html 文件中使用的 div 元素的 innerHTML:

这是包含 HTML 部分和请求数据的 JavaScript 方法的代码。为了得到一个JSON对象作为响应,我们使用了XMLHttpRequest.responseType = ‘json’属性。

HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content= 
        "width=device-width, initial-scale=1.0"> 
</head> 
  
<body> 
    <h1 style="color:green"> 
        GeeksforGeeks 
    </h1> 
  
    <h3> 
        XMLHttpRequest.responseType = "json" property 
    </h3> 
  
    <div id="resonse_box" 
        style="border: 2px solid gray;  
               width:400px; height:auto;  
               padding:20px;  
               border-radius:0.5rem; "> 
        Waiting for response from server ... 
    </div><br> 
  
    <button onclick="callxmlrequest()" 
        style="padding:0.5rem;  
               background-color:rgba(2, 2, 174, 0.719);  
               border:0px; border-radius:0.3rem;  
               color:white;  
               cursor:pointer"> 
        ClickMe to get Response 
    </button> 
  
    <script> 
        const callxmlrequest = () => { 
  
            // Create a new XMLHttpRequest object -  
            let XMLHttpRequest_object  
                = new XMLHttpRequest(); 
  
            // Set the Response type -  
            XMLHttpRequest_object.responseType = "json"; 
  
            // Set up a callback function to  
            // handle the response -  
            XMLHttpRequest_object.onload = function () { 
                if (XMLHttpRequest_object.status === 200) { 
                    var res = JSON.stringify( 
                        XMLHttpRequest_object.response); 
                    document.getElementById( 
                        "resonse_box").innerHTML = res; 
                } else { 
                    document.getElementById("resonse_box") 
                        .innerHTML = "Request Failed!"; 
                } 
            }; 
  
            // Open a new request with the GET  
            // method and the URL of the server 
            XMLHttpRequest_object.open( 
                'GET',  
                './GeeksforGeeks.json' 
            ); 
  
            // Send the request to the server 
            XMLHttpRequest_object.send(); 
        } 
    </script> 
</body> 
  
</html> 

输出:

XMLHttpRequest.responseType 属性

示例2: 在这个示例中,我们使用XMLHttpRequest调用和XMLHttpRequest.responseType = ‘document’属性来请求一个HTML文档。我们创建了一个带有基本标签的HTML页面,并为响应提供了链接到函数的链接。在获得响应之后,将其转换为字符串并更新元素的InnerHTML。

HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content= 
        "width=device-width, initial-scale=1.0"> 
</head> 
  
<body> 
    <h1 style="color:green"> 
        GeeksforGeeks 
    </h1> 
  
    <h3> 
        XMLHttpRequest.responseType = "document" property 
    </h3> 
  
    <div id="resonse_box" style="border: 2px solid gray;  
           width:600px; height:auto;  
           padding:20px;  
           border-radius:0.5rem; "> 
  
        Waiting for response from server ..... 
  
    </div><br> 
    <button onclick="callxmlrequest()" 
        style="padding:0.5rem;  
               background-color:rgba(2, 2, 174, 0.719);  
               border:0px; border-radius:0.3rem;  
               color:white; cursor:pointer"> 
        Click Me to get Response 
    </button> 
  
    <script> 
        const callxmlrequest = () => { 
  
            // Create a new XMLHttpRequest object -  
            let XMLHttpRequest_object = new XMLHttpRequest(); 
  
            // Set the Response type -  
            XMLHttpRequest_object.responseType = "document"; 
  
            // Set up a callback function to handle the response -  
            XMLHttpRequest_object.onload = function () { 
                if (XMLHttpRequest_object.status === 200) { 
  
                    var res = new XMLSerializer() 
                        .serializeToString(XMLHttpRequest_object.response); 
                    document.getElementById("resonse_box").innerHTML = res; 
                } else { 
                    document.getElementById("resonse_box") 
                        .innerHTML = "Request Failed!"; 
                } 
            }; 
  
            // Open a new request with the GET  
            // method and the URL of the server 
            XMLHttpRequest_object.open('GET', './GFG.html'); 
  
            // Send the request to the server 
            XMLHttpRequest_object.send(); 
        } 
    </script> 
</body> 
  
</html> 

输出:

XMLHttpRequest.responseType 属性

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程