Qt WebView js交互(new) 支持ios android 平臺
由于服務(wù)器和HTML界面在同一個進(jìn)程,因此傳輸速度很快,不用考慮傳輸速度問題。
并且C++端放在本地可以做本地App應(yīng)用,放在服務(wù)器,可以做網(wǎng)頁應(yīng)用。
原理是 ?界面中 new Qt HTTP服務(wù)器,
HTML端用JavaScript XMLHttpRequest發(fā)送請求給C++(可包含參數(shù) 參數(shù)中使用字符串用來表示,函數(shù)可以用HTTP 子域開表示,),C++根據(jù)傳入的字符串,調(diào)用Qt元函數(shù),或者封裝入Qt quick中,調(diào)用eval.推薦用Qt quick封裝,因為更方便,他里面封裝好了ios 和 android的Webview
返回值由C++ HTTP服務(wù)器端返回。
因為直接是Qt和javasc交互,因此跳過了中間層
傳統(tǒng):
C++ ? —> ? ?JAVA(objecttive C) ? ?—> ? JavaScript
C++ ? <— ? ?JAVA(objecttive C) ? ?<—- ?JavaScript
現(xiàn)在:C++ ?
DEMO:
int??testdata=0;
void?Helloworldcontroller3::service(HttpRequest?&request,?HttpResponse?&response)?{
????//允許跨域
??????response.setHeader("Access-Control-Allow-Origin",?"*");
????QByteArray?path=request.getPath();
????????qDebug("RequestMapper:?path=%s",path.data());
?????????if?(path=="/test")?{
????????????//獲取參數(shù)
????????????QByteArray?m_id=request.getParameter("p1");
????????????QString??s;
????????????s.sprintf("data?%d",m_id.toInt());
????????????response.setStatus(200,"ok");??//返回成功代碼200??已經(jīng)代碼字符串
????????????response.write(s.toStdString().c_str(),true);//寫入?yún)?shù)
????????????testdata++;
????????}
????????else?{
????????????response.setStatus(404,"oo!Not?found");
????????????QString??s?=QString::fromLocal8Bit("未知的連接哦");
????????????QByteArray?s2(s.toStdString().c_str());
????????????response.write(s2,true);
????????}
????????qDebug("RequestMapper:?finished?request");
}var?xhr;
function???異步CALL_Test(arg1)
{
????if?(!xhr)
????{
????????xhr?=?new?XMLHttpRequest();
????}
????if?(xhr)?{
????????//寫入?yún)?shù)
????????xhr.open('POST',?"http://localhost:8080/test?p1="+arg1,?true);//異步調(diào)用?發(fā)送給Qt端
????????xhr.onreadystatechange?=?function(evtXHR){
????????????if?(xhr.readyState?==?4)?{
????????????????if?(xhr.status?==?200)?{//如果發(fā)送成功??
????????????????????var?response?=?xhr.responseText;//獲取Qt返回值??作為新建列表的標(biāo)題
????????????????????alert(response)
????????????????????$("#list1").append('Inbox'+response+'');
????????????????????$("#list1").listview("refresh");
????????????????}?else?{
????????????????????alert(??"不允許跨域請求。"?+?xhr.status+xhr.responseText);
????????????????}
????????????}
????????};
????????xhr.send(null);
????}?else?{
????????alert("Sorry!程序出錯!Code?Postion:XML?ERROR:1")
????}
???//?alert("end");
}?
????$(function(){
???????$("button").click(function(){
???????????異步CALL_Test(123);
??});
}); 




