如何在QML應(yīng)用中使用Javascript解析JSON
來(lái)源:程序員人生 發(fā)布時(shí)間:2015-05-29 07:55:22 閱讀次數(shù):7002次
很多QML應(yīng)需要訪問(wèn)web services。我們可以通過(guò)Javascript的方法來(lái)解析得到我們所需要的JSON數(shù)據(jù),并把它們展現(xiàn)出來(lái)。在今天的例子中,我們將展現(xiàn)如何實(shí)現(xiàn)它?
我們可以創(chuàng)建1個(gè)最基本的“QML App with Simple UI (qmlproject)”,并取名我們的利用為“baidutranslator”。我們將使用的API為:
http://openapi.baidu.com/public/2.0/bmt/translate?client_id=2hG67S2yRm5chkr62j2IEmYL&from=auto&to=auto&q=%E4%BD%A0%E5%A5%BD
顯示的結(jié)果為:
{"from":"zh","to":"en","trans_result":[{"src":"u4f60u597d","dst":"Hello"}]}
我們可以通過(guò)這個(gè)API的接口來(lái)得到中文或英文的翻譯,乃至我們可以得到1個(gè)完全句子的中文或英文。上面接口返回的結(jié)果是JSON格式的。
為了能夠解析我們得到的JSON格式,我們創(chuàng)建了1個(gè)“jsonparser.js”文件:
var URL = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=2hG67S2yRm5chkr62j2IEmYL&from=auto&to=auto&q=";
function startParse(keyword, callback) {
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.HEADERS_RECEIVED) {
} else if (doc.readyState === XMLHttpRequest.DONE) {
if(doc.status != 200) {
console.log("!!!Network connection failed!")
}
else {
console.log("got some results!");
if(doc.responseText == null) {
}
else {
console.log("result: ", doc.responseText)
var json = JSON.parse('' + doc.responseText+ '');
json["status"] = "OK";
callback.update(json);
}
}
}
}
doc.open("GET", URL + keyword);
doc.send();
}
我們通過(guò)“startParse”來(lái)發(fā)送要求,并通過(guò)JSON.parse()來(lái)解析我們得到的結(jié)果。我們通過(guò)“callback.update”來(lái)返回到我們的QML設(shè)計(jì)中。
“Main.qml”的設(shè)計(jì)以下:
import QtQuick 2.0
import Ubuntu.Components 1.1
import "jsonparser.js" as API
/*!
rief MainView with a Label and Button elements.
*/
MainView {
id: root
// objectName for functional testing purposes (autopilot-qt5)
objectName: "mainView"
// Note! applicationName needs to match the "name" field of the click manifest
applicationName: "baidutranslator.liu-xiao-guo"
/*
This property enables the application to change orientation
when the device is rotated. The default is false.
*/
//automaticOrientation: true
// Removes the old toolbar and enables new features of the new header.
useDeprecatedToolbar: false
width: units.gu(60)
height: units.gu(85)
function update(json) {
console.log("json: " + JSON.stringify(json));
mymodel.clear();
if ( json.trans_result !== undefined && json.trans_result.length !== undefined ) {
for ( var idx = 0; idx < json.trans_result.length; idx++ ) {
if ( json.trans_result[ idx ].dst ) {
console.log( 'meaning: ' + json.trans_result[ idx ].dst);
mymodel.append( {"meaning": json.trans_result[ idx ].dst });
}
}
} else {
mymodel.clear();
}
}
Page {
title: i18n.tr("Baidu translator")
ListModel {
id: mymodel
}
Column {
spacing: units.gu(1)
anchors {
margins: units.gu(2)
fill: parent
}
TextField {
id: input
placeholderText: "Please input a word"
width: parent.width
text: "你好"
onTextChanged: {
mymodel.clear();
var json = API.startParse(input.text, root);
}
}
Button {
id: doit
width: parent.width
text: i18n.tr("Translate")
onClicked: {
var json = API.startParse(input.text, root);
}
}
ListView {
id: listview
width: parent.width
height: parent.height - input.height - doit.height
model: mymodel
delegate: Text {
text: modelData
}
}
}
}
}
這里我們通過(guò)“
update”來(lái)更新我們的ListView。

所有項(xiàng)目的源碼是在:git clone https://gitcafe.com/ubuntu/baidutranslator.git
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)