gpt4 book ai didi

qt - QML 中的超时 XMLHttpRequest

转载 作者:行者123 更新时间:2023-12-01 08:41:53 25 4
gpt4 key购买 nike

如何使 QML 中的 XMLHttpRequest 超时?我有以下代码,但它不会超时。似乎超时功能没有实现!?还有其他方法可以实现超时吗?

var http = new XMLHttpRequest();
http.open("POST", "http://localhost/test.xml", true);
http.setRequestHeader('Content-type', 'application/json; charset=utf-8')

http.timeout = 4000;
http.ontimeout = function () {
console.log("timed out")
}

http.onreadystatechange = function() {
if (http.readyState === XMLHttpRequest.DONE) {
// Do something
}
}

http.send(JSON.stringify(data));

编辑:代码不在qml中,而是在js文件中。而且它不会进入 qml 文件,因为它是模型 (MVC) 的一部分。

最佳答案

看来QML XMLHttpRequest 不支持timeout 功能。这是支持的函数/属性子集的列表:

http://qt-project.org/doc/qt-5/qtqml-javascript-qmlglobalobject.html#xmlhttprequest

但是你可以使用 QML Timer 项来达到这个目的,例如:

import QtQuick 2.3

Item {
id: root
width: 600
height: 400

Text {
anchors.fill: parent
id: response
text: "Click me"
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
MouseArea {
anchors.fill: parent
onClicked: {
response.text = "Loading...";

var req = new XMLHttpRequest();

var timer = Qt.createQmlObject("import QtQuick 2.3; Timer {interval: 4000; repeat: false; running: true;}",root,"MyTimer");
timer.triggered.connect(function(){
req.abort();
response.text = "timed out";
});


req.open("GET","http://google.com--",true); // correct me
req.onreadystatechange = function() {

if (req.readyState === XMLHttpRequest.DONE && req.status == 200) {
response.text = req.getAllResponseHeaders();
timer.running = false;
}
}

req.send();
}
}
}
}

关于qt - QML 中的超时 XMLHttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26598404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com