由于当前C++项目需要使用ajax库去post调用ashx接口
由于当前C++项目需要使用ajax库去post挪用ashx接口,接口地点如下所示:
需要通报的参数如下:
然后发明qml对照好挪用ajax.js库,所以本章通过C++界面去获取qml要领来实现挪用ashx接口(以一个C++界面demo措施为例)
1.抓post数据
通过网页获取到的post数据如下所示:
所以盘问20191121~20191122期间时则填入内容: "deptCode=021&startDate=20191121&endDate=20191122"
2.导入ajax.js库
ajax.js文件如下所示:
// GET function get(url, success, failure) { var xhr = new XMLHttpRequest; xhr.open("GET", url); xhr.onreadystatechange = function() { handleResponse(xhr, success, failure); } xhr.send(); } // POST function post(url, arg, success, failure) { var xhr = new XMLHttpRequest; xhr.open("POST", url); xhr.setRequestHeader("Content-Length", arg.length); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); //用POST的时候必然要有这句 xhr.onreadystatechange = function() { handleResponse(xhr, success, failure); } xhr.send(arg); } // 措置惩罚惩罚返回值 function handleResponse(xhr, success, failure){ if (xhr.readyState == XMLHttpRequest.DONE) { if (xhr.status == 200){ if (success != null && success != undefined) { var result = xhr.responseText; try{ success(result, JSON.parse(result)); }catch(e){ success(result, {}); } } } else{ if (failure != null && failure != undefined) failure(xhr.responseText, xhr.status); } } }
3.写main.qml
import QtQuick 2.3 import QtQuick.Window 2.2 import "ajax.js" as Ajax Item { function getWrenchTools(deptCode,startDate,endDate) { console.log("Got message:", deptCode,startDate,endDate) //打印参数数据 Ajax.post("","deptCode="+deptCode+"&startDate="+startDate+"&endDate="+endDate+"", Widget.invokeFunc); }
这里暗示界说一个getWrenchTools()要领,当post告成并返回数据时,则挪用Widget.invokeFunc()回调函数(Widget: 该qml对应的C++类,后面会讲怎么绑缚的)
4.widget界面如下
然后写widget.h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QString> #include <QDebug> #include <QTimer> #include <QQmlApplicationEngine> #include <QQmlComponent> namespace Ui { class widget; } class widget : public QWidget { Q_OBJECT QQmlApplicationEngine engine; QObject *engineObject; //指向运行的qml东西 public: explicit widget(QWidget *parent = 0); ~widget(); private: Ui::widget *ui; public: Q_INVOKABLE void invokeFunc(QVariant data1,QVariant data2); private slots: void on_pushButton_clicked(); }; #endif // WIDGET_H
写widget.cpp
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/33203.html