XMLHttpRequest QML Type

用于向服务器发送请求的对象。更多

Import Statement: import QtQml

属性

方法

详细说明

XMLHttpRequest 对象允许脚本执行 HTTP 客户端功能,如提交表单数据或从服务器异步加载数据。

XMLHttpRequest API 是W3C XHR 1 级标准的部分实现,但有以下例外:

  • 它不执行同源策略。

发送请求

使用XMLHttpRequest API 发送请求的步骤如下:

  1. 创建XMLHttpRequest 对象。
  2. onreadystatechange 信号处理器分配一个回调函数。
  3. 使用适当的 HTTP 方法和 URL 调用open()。
  4. 调用send()

回调函数处理请求的 HTTP 响应。在使用以下方法读取响应之前,最好先在处理程序中检查readyState 是否为DONE

下面的示例演示了如何发送请求并读取响应:

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 {}
           }
      }
}

前面的代码段将按钮的点击信号连接到一个外部sendRequest 函数。第一个参数传递的是资源 URL,第二个参数传递的是处理用户界面更新的回调函数。sendRequest 函数存在于外部request.js 文件中,可以这样实现:

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();
}

前面的代码段遵循了开头提到的四个简单步骤。它首先实例化了XMLHttpRequest 对象,并分配了一个回调函数来处理响应。在向服务器发送请求之前,它还使用 HTTP 方法和 URL 调用了open()。请注意,sendRequest 的第二个参数是在onreadystatechange 的末尾调用的,以便根据 HTTP 响应处理 UI 更新。

如果要调试请求,请将QML_XHR_DUMP 环境变量设置为1 。这将记录以下信息:

  • 发送请求的方法类型(GET 或 POST)、URL 和正文。
  • 收到的响应的 URL 和正文。
  • 网络错误(如果有)。

访问本地文件

默认情况下,不能使用XMLHttpRequest 对象从本地文件系统读取文件。如果希望使用此功能访问本地文件,可将以下环境变量设置为1

  • qml_xhr_allow_file_read
  • qml_xhr_allow_file_write

警告: 只有在知道应用程序运行可信的 QML 和 JavaScript 代码时,才可使用此功能。

responseXML 文档

QML 当前支持的responseXML XML DOM 树是网络浏览器支持的DOM Level 3 CoreAPI 的缩减子集。QML 实现支持以下对象和属性:

节点文档元素属性字符数据文本
  • 节点名称
  • 节点值
  • 节点类型
  • 父节点
  • 子节点
  • 第一个子节点
  • 最后一个子节点
  • 上一个同辈节点
  • 下一个同辈节点
  • 属性
  • xml 版本
  • xmlEncoding
  • xmlStandalone
  • 文档元素
  • 标签名称
  • 名称
  • 所有者元素
  • 数据
  • 长度
  • isElementContentWhitespace
  • wholeText

属性文档

onreadystatechange : function

选择一个回调函数,以便在XMLHttpRequest 对象的readyState 发生变化时调用。

另请参阅 readyState


readyState : enumeration [read-only]

表示XMLHttpRequest 对象的当前状态。

该值可以是以下值之一:

常量说明
XMLHttpRequest.UNSENT请求未初始化,即调用open() 之前的状态。
XMLHttpRequest.OPENED请求已初始化,即之前调用过open() 但没有进一步进展。
XMLHttpRequest.HEADERS_RECEIVED收到服务器的回复,但请求尚未完全处理。
XMLHttpRequest.LOADING正在从服务器下载数据。
XMLHttpRequest.DONE请求处理完毕。

另请参阅 onreadystatechange


response : var [read-only]

根据最后一次请求的responseType ,返回StringArrayBufferDocument

另请参阅 responseTyperesponseTextresponseXML


responseText : string [read-only]

返回String ,其中包含从最后一次响应接收到的数据。

另请参阅 responseXML


responseType : string

返回String ,说明最后收到的响应的内容类型。

  • 如果响应类型为 "text "或空String ,则响应内容为UTF-16 编码的String
  • 如果响应类型为 "arraybuffer",则表示响应内容是包含二进制数据的ArrayBuffer
  • 如果响应类型为 "json",则响应内容应为 JSONDocument
  • 如果响应类型为 "document",则表示响应内容为 XMLDocument ,可以使用responseXML 属性安全读取。

另请参阅 response


responseURL : string [read-only, since 6.6]

在发生任何重定向后,返回用于检索响应数据的 url。

此属性在 Qt 6.6 中引入。


responseXML : var [read-only]

如果响应内容无法解析为 XML 或 HTML,则返回Documentnull 。有关详细信息,请参阅responseXML document 部分。

另请参阅 responseText


status : int [read-only]

返回最后收到的响应的状态代码。

另请参阅 statusText


statusText : string [read-only]

返回String ,其中包含与最后收到的响应的状态代码相关联的状态信息。

另请参阅 status


方法文档

void abort()

取消当前请求。

它将readyState 属性改为XMLHttpRequest.UNSENT ,并发出readystatechange 信号。


string getAllResponseHeaders()

返回String 上一次收到的响应头。

以下是一个响应头示例:

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)

返回上次响应的headerName 值,如果缺少headerName ,则返回空的String

另请参阅 getAllResponseHeaders()。


void open(method, url, async)

指定您希望请求使用的 HTTPmethod ,以及您希望请求的url 。应确保总是在调用send() 之前调用该函数。第三个可选参数async 可用于决定请求是否应该是异步的。默认值为true

发出readystatechange 信号,调用onreadystatechange 处理程序,并将readyState 属性设置为XMLHttpRequest.OPENED


[since 6.6] void overrideMimeType(mime)

强制XMLHttpRequest 将下一次 HTTP 响应中接收到的数据解释为 MIME 类型mime ,而不是服务器提供的类型。

此方法在 Qt 6.6 中引入。


void send(data)

向服务器发送请求。您可以使用可选参数data 在请求正文中添加额外数据。这对 POST 请求非常有用,因为您通常希望请求包含额外的数据。

从服务器收到响应后,在处理响应的过程中,readyState 属性会被更新。首先会设置为HEADERS_RECEIVED ,然后是LOADING ,最后是DONE 。每次更新readyState 时,都会发出readystatechange 信号。


void setRequestHeader(header, value)

为下一个要发送的请求添加一个新标头。这是一个键值对,名称是header ,对应的是value


© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.