每个GET请求的QWebView加载页面失败

时间:2014-04-02 11:43:23

标签: javascript c++ ajax qt qwebview

我正试图在QWebView中嵌入的JavaScript中通过GET加载网站。如果我使用jQuery.ajax,则会给我一个错误。解决方案是采用XMLHttpRequest

这是我的JavaScript代码:

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

它在Chrome中运行得很好。如果我执行我的Qt应用程序并加载文件:

QNetworkProxyFactory::setUseSystemConfiguration(true);

ui->webView->load(QUrl("qrc:///index.html"));
ui->webView->show();

我收到此错误:

Error message

我做错了什么?

1 个答案:

答案 0 :(得分:0)

这是我的解决方案,对我有用:

<强>的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;
}