How do I time out a XMLHttpRequest in QML? I have the following code, but it won't time out. It seems the timeout functionality is not implemented!? Is there any other way to achieve timeouts?
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));
Edit: The code is not in a qml, but in a js file. And it won't go into a qml file as it is part of the model (MVC).
It looks that QML
XMLHttpRequest
does not support timeout
function.
This is a list of supported subset of functions/properties:
http://qt-project.org/doc/qt-5/qtqml-javascript-qmlglobalobject.html#xmlhttprequest
But you can use QML
Timer
item for this purposes, for example:
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();
}
}
}
}