I'm trying to load a site via GET in JavaScript embeeded in QWebView
. If I use jQuery.ajax
it gives me an error. The solution is to take the XMLHttpRequest
.
This is my JavaScript code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = jQuery.parseXML(xmlhttp.responseText);
alert(data);
} else if (xmlhttp.readyState == 4) {
alert(JSON.stringify(xmlhttp));
}
}
xmlhttp.open("GET", CO_SERVICE, true);
xmlhttp.setRequestHeader("Authorization", "Basic " + btoa("user:password"));
xmlhttp.send();
It works just fine in Chrome. If I execute my Qt application and load the file with:
QNetworkProxyFactory::setUseSystemConfiguration(true);
ui->webView->load(QUrl("qrc:///index.html"));
ui->webView->show();
I get this error:
What am I doing wrong?
This is my solution, which worked for me:
JavaScript
this.done = function (value) {
console.log(value);
};
getRequest.done.connect(this, done);
getRequest.get("url", "username", "password");
C++
MainWindow.h
private:
Ui::MainWindow *ui;
GetRequest* mGetRequest;
private slots:
void addJSObject();
MainWindow.cpp
mGetRequest = new GetRequest();
QObject::connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addJSObject()));
ui->webView->load(QUrl("qrc:/index.html"));
void MainWindow::addJSObject() {
ui->webView->page()->mainFrame()->addToJavaScriptWindowObject(QString("getRequest"), mGetRequest);
}
GetRequest.h
#ifndef GETREQUEST_H
#define GETREQUEST_H
#include <QObject>
#include <QString>
#include <QNetworkReply>
#include <QNetworkAccessManager>
class GetRequest : public QObject {
Q_OBJECT
public:
explicit GetRequest(QObject *parent = 0);
~GetRequest();
public slots:
void get(QString url, QString username, QString password);
signals:
void done(QString value);
private:
QNetworkAccessManager* mNetworkAccessManager;
private slots:
void replyFinished(QNetworkReply* networkReply);
};
#endif // GETREQUEST_H
GetRequest.m
#include "getrequest.h"
GetRequest::GetRequest(QObject *parent) : QObject(parent) {
mNetworkAccessManager = new QNetworkAccessManager(this);
QObject::connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}
GetRequest::~GetRequest() {
delete mNetworkAccessManager;
}
void GetRequest::get(QString url, QString username, QString password) {
QUrl u(url);
u.setUserName(username);
u.setPassword(password);
mNetworkAccessManager->get(QNetworkRequest(u));
}
void GetRequest::replyFinished(QNetworkReply* networkReply) {
QString value(networkReply->readAll());
emit done(value);
delete networkReply;
}