Reproducible example in QML:
main.cpp
#include <QSsl>
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.0
Window {
visible: true
width: 640
height: 480
Component.onCompleted: getPage(logResults)
function logResults(results) {
console.log("RESULTS: " + results)
}
function getPage(callback) {
var xhttp = new XMLHttpRequest();
var url = "https://www.google.com/"
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4 && xhttp.status === 200) {
console.log("calling callback")
callback(xhttp.responseText)
}
};
xhttp.open("GET", url);
xhttp.send();
}
}
Output I get:
qml: calling callback
Output I expect:
qml: calling callback
qml: RESULTS: <the HTML located at https://www.google.com/>
The xhttp.responseText
is not empty or undefined, in fact the console.log()
throws no errors. Reformat the code like so:
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4 && xhttp.status === 200) {
console.log("Am I alive?")
console.log("response text: " + xhttp.responseText)
console.log("I am alive")
}
};
then I get output:
qml: Am I alive?
qml: I am alive
Why does XMLHttpRequest responseText not exist? Why does it kill the console.log() and not throw an 'undefined' or some other error? Is there a better way to scrape the html from this web page?