开发者

Weird behavior of JavaScript with QML

开发者 https://www.devze.com 2023-04-06 07:52 出处:网络
weird behavior of java script. I am trying to develop a simple example application using QT-QML and JavaScript.

weird behavior of java script. I am trying to develop a simple example application using QT-QML and JavaScript.

In this i am using HTTP Requests, I have on Button that sends HTTP request using JavaScript.

When I receive response of the HTTP request in the call back function i am trying to read the state of the HTTP response as follows.

if( httpReq.readyState == 4 ) //Problem
{   
    if(httpReq.status == 200 )
    {
           ...

I am trying to check if readyState is 4 (4 represents complete/done)

But if conditions fails to check this and gets evaluated to true regardless of readyState value.

For example, if readyState is 0 (0 == 4) then also if condition gets evaluated to TRUE which should not.

Why this might be happening.

I have also tried

 1. if( parseInt(httpReq.readyState) == 4 ) 
 2. if( Number(httpReq.readyState) == 4 )  
 3. if( httpReq.readyState == '4' )  

Above conditions also give the same results and gets evaluated to TRUE regardless of readyState value.

Is there any problem with my JavaScript Interpreter.

Thanks.

------UPDATE-----

Thing is that, I have QML application (which sends HTTP request) and HTTP server (Which servers this QML HTPP request) both in the same application/process. When I Separate HTTP server and QML application in two different application/executable it does work, and when i combine both the applications in same executable then it creates problem. When i combine both HTTP server and QML application in one executable QML JavaScript i开发者_开发问答nterpreter starts behaving weird. I am running QML application in a Separate Thread before running Web server.


Did you try:

if( httpReq.readyState == 4 ) //Problem
{   
  console.log("Evaluated to true with: " + httpReq.readyState);

...

To assert that the condition was truly evaluated to true with a wrong integer?

Alternatively, since you call this in QML, this might come from the way you use javascript with QML, can you show how you invoke the javascript from the QML?


A minimal example with the described behaviour would be helpful.

The following code works for me without problems:

import QtQuick 1.0

Item {
    Component.onCompleted: {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function() {
            console.log("readyState: " + req.readyState);

            if (req.readyState == XMLHttpRequest.DONE) { // 4 instead of 'XMLHttpRequest.DONE' works here too
                console.log("Request complete");

                if (req.status == 200) {
                    console.log("Status code: 200");
                    console.log(req.responseText.slice(0, 50) + "...")
                }
            }
        }

        req.open("GET", "http://stackoverflow.com/");
        req.send();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消