QML 中的超时 XMLHttpRequest [英] Timeout XMLHttpRequest in QML

查看:96
本文介绍了QML 中的超时 XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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).

推荐答案

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

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

但是您可以使用 QML Timer 项用于此目的,例如:

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

这篇关于QML 中的超时 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆