本页

XMLHttpRequest JavaScript 对象

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

void XMLHttpRequest::abort()

取消当前请求。

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

string XMLHttpRequest::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

字符串 XMLHttpRequest::getResponseHeader(headerName)

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

void XMLHttpRequest::open(method, url, async)

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

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

void XMLHttpRequest::send(data)

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

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

void XMLHttpRequest::setRequestHeader(header, value)

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

void XMLHttpRequest::overrideMimeType(mime)

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

函数 XMLHttpRequest::onreadystatechange

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

枚举 XMLHttpRequest::readyState

表示XMLHttpRequest 对象的当前状态。

该值可以是以下值之一:

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

字符串 XMLHttpRequest::responseURL

在发生重定向后,返回用于获取响应数据的 URL。

字符串 XMLHttpRequest::responseText

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

var XMLHttpRequest::responseXML

如果响应内容无法解析为 XML 或 HTML,则返回Documentnull 。更多信息请参阅responseXML 文档部分。

var XMLHttpRequest::response

根据上次请求的responseType,返回StringArrayBufferDocument

字符串 XMLHttpRequest::responseType

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

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

int XMLHttpRequest::status

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

字符串 XMLHttpRequest::statusText

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

另请参阅 getResponseHeader()getAllResponseHeaders()readyStateonreadystatechangeresponseXMLresponseTextresponseTyperesponsestatusTextstatus

© 2026 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.