XMLHttpRequest QML Type

Object for sending requests to a server. 更多...

import 语句: import QtQml

特性

方法

详细描述

The XMLHttpRequest object allows scripts to perform HTTP client functionality, such as submitting form data or loading data asynchronously from a server.

The XMLHttpRequest API is a partial implementation of the W3C XHR Level 1 standard with the following exception:

  • It does not enforce the same origin policy.

Sending requests

Use the following steps to send a request using the XMLHttpRequest API:

  1. 创建 XMLHttpRequest 对象。
  2. Assign a callback function to the onreadystatechange signal handler.
  3. 调用 open () with the appropriate HTTP method and URL to request.
  4. 调用 send ()

The callback function handles the HTTP response for a request. It's a good practice to check if the readyState is DONE in the handler, before you use one of the following methods to read the response:

The following example demonstrates how to send a request and read the response:

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import "request.js" as XHR
ApplicationWindow {
      width: 640
      height: 640
      visible: true
      ColumnLayout {
           anchors.fill: parent
           RowLayout {
               Layout.fillWidth: true
               TextField {
                   id: urlTextField
                   text: "https://www.example.com/index.html"
                   Layout.fillWidth: true
               }
               Button {
                   text: qsTr("Send!")
                   onClicked: XHR.sendRequest(urlTextField.text, function(response) {
                       statusTextField.text = response.status;
                       let isPlainText = response.contentType.length === 0
                       contentTypeTextField.text = isPlainText ? "text" : response.contentType;
                       if (isPlainText)
                           contentTextArea.text = response.content;
                   });
               }
           }
           GridLayout {
               columns: 2
               Layout.fillWidth: true
               Label {
                   text: qsTr("Status code")
                   Layout.fillWidth: true
               }
               Label {
                   text: qsTr("Response type")
                   Layout.fillWidth: true
               }
               TextField {
                    id: statusTextField
                    Layout.fillWidth: true
               }
               TextField {
                    id: contentTypeTextField
                    Layout.fillWidth: true
               }
           }
           Flickable {
               clip: true
               contentWidth: contentTextArea.width
               contentHeight: contentTextArea.height
               Text {
                    id: contentTextArea
               }
               Layout.fillWidth: true
               Layout.fillHeight: true
               ScrollBar.vertical: ScrollBar {}
               ScrollBar.horizontal: ScrollBar {}
           }
      }
}
					

The earlier snippet connects the button's clicked signal to an external sendRequest function. A resource URL is passed as the first argument, and a callback function to handle UI updates is passed as the second. The sendRequest function, which exists in an external request.js file, can be implemented like this:

function sendRequest(url, callback)
{
    let request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState === XMLHttpRequest.DONE) {
            let response = {
                status : request.status,
                headers : request.getAllResponseHeaders(),
                contentType : request.responseType,
                content : request.response
            };
            callback(response);
        }
    }
    request.open("GET", url);
    request.send();
}
					

The earlier snippet follows the four simple steps mentioned at the beginning. It instantiates the XMLHttpRequest object first, and assigns a callback function to handle the response. It also calls open () with an HTTP method and URL, before it sends the request to the server. Notice that the second argument to sendRequest is called at the end of onreadystatechange , in order to handle UI updates based on the HTTP response.

设置 QML_XHR_DUMP 环境变量到 1 if you want to debug a request. This will log the following information:

  • Method type (GET or POST), URL, and body of sent requests.
  • URL and body of responses received.
  • Network error, if any.

Accessing local files

By default, you cannot use the XMLHttpRequest object to read files from your local file system. If you wish to use this feature to access local files, you can set the following environment variables to 1 .

  • QML_XHR_ALLOW_FILE_READ
  • QML_XHR_ALLOW_FILE_WRITE

警告: Use this feature only if you know that the application runs trusted QML and JavaScript code.

responseXML document

The responseXML XML DOM tree currently supported by QML is a reduced subset of the DOM Level 3 Core API supported in a web browser. The following objects and properties are supported by the QML implementation:

Node Document 元素 Attr CharacterData 文本
  • nodeName
  • nodeValue
  • nodeType
  • parentNode
  • childNodes
  • firstChild
  • lastChild
  • previousSibling
  • nextSibling
  • 属性
  • xmlVersion
  • xmlEncoding
  • xmlStandalone
  • documentElement
  • tagName
  • 名称
  • ownerElement
  • data
  • length
  • isElementContentWhitespace
  • wholeText

特性文档编制

onreadystatechange : function

Choose a callback function you want to get invoked whenever the readyState XMLHttpRequest object changes.

另请参阅 readyState .

readyState : enumeration [read-only]

Indicates the current state of the XMLHttpRequest 对象。

The value can be one of the following:

常量 描述
XMLHttpRequest.UNSENT The request is not initialized, which is the state before calling open ().
XMLHttpRequest.OPENED The request is initialized, meaning open () was previously called, but no further progress.
XMLHttpRequest.HEADERS_RECEIVED Received a reply from the sever, but the request is not fully processed yet.
XMLHttpRequest.LOADING Downloading data from the server.
XMLHttpRequest.DONE Finished processing the request.

另请参阅 onreadystatechange .

response : var [read-only]

Returns either a 字符串 ArrayBuffer ,或 Document , depending on the responseType of the last request.

另请参阅 responseType , responseText ,和 responseXML .

responseText : string [read-only]

返回 字符串 containing the data received from the last response.

另请参阅 responseXML .

responseType : string

返回 字符串 describing the content type of the last response received.

  • If the response type is "text" or an empty 字符串 , the response content is a UTF-16 encoded 字符串 .
  • If the response type is "arraybuffer", it means that the response content is an ArrayBuffer containing binary data.
  • If the response type is "json", the response content should be a JSON Document .
  • If the response type is "document", it means that the response content is an XML Document , which can be safely read with the responseXML 特性。

另请参阅 response .

responseURL : string [read-only, since 6.6]

Returns the url that was used to retrieve the response data, after any redirects have occurred.

该特性在 Qt 6.6 引入。

responseXML : var [read-only]

Returns either a Document ,或 null , if the response content cannot be parsed as XML or HTML. See the responseXML document section for more information.

另请参阅 responseText .

status : int [read-only]

Returns the status code for the last response received.

另请参阅 statusText .

statusText : string [read-only]

返回 字符串 that has the status message associated with the status code for the last response received.

另请参阅 status .

方法文档编制

void abort ()

Cancels the current request.

It changes the readyState property to be XMLHttpRequest.UNSENT 并发射 readystatechange 信号。

string getAllResponseHeaders ()

返回 字符串 of headers received from the last response.

The following is an example response header:

content-encoding: gzip
content-type: text/html; charset=UTF-8
date: Mon, 06 Feb 2023 09:00:08 GMT
expires: Mon, 13 Feb 2023 09:00:08 GMT
last-modified: Thu, 17 Oct 2019 07:18:26 GMT
					

另请参阅 getResponseHeader ().

string getResponseHeader ( headerName )

Returns either the headerName value from the last response, or an empty 字符串 , if the headerName is missing.

另请参阅 getAllResponseHeaders ().

void open ( method , url , async )

Specify the HTTP method you want the request to use, as well as the url you wish to request. You should make sure to always call this function before send (). An optional third parameter async can be used to decide whether the request should be asynchronous or not. The default value is true .

Emits the readystatechange signal, which calls the onreadystatechange handler with the readyState 特性被设为 XMLHttpRequest.OPENED .

[since 6.6] void overrideMimeType ( mime )

Forces the XMLHttpRequest to interpret the data received in the next HTTP response, as if it had the MIME type mime , rather than the one provided by the server.

This method was introduced in Qt 6.6.

void send ( data )

Sends the request to the server. You can use the optional argument data to add extra data to the body of the request. This can be useful for POST requests, where you typically want the request to contain extra data.

The readyState property is updated once a response has been received from the server, and while the response is being processed. It will first be set to HEADERS_RECEIVED , then to LOADING , and finally DONE , once the response has been fully processed. The readystatechange signal is emitted every time readyState is updated.

void setRequestHeader ( header , value )

Adds a new header to the next request you wish to send. This is a key-value pair, which has the name header 和相应 value .