我刚刚开始研究QML,它看起来很有希望,因为我非常喜欢C。在实验中,我不得不使用Ajax请求从一个ListModel服务中更新一个PHP。我提到了这链接,但我似乎无法让它工作。我的代码如下。
try.js:
function load() {
listModel.clear();
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://<url>/service_newsletter.php?method=news", true);
xhr.onreadystatechange = function() {
if(xhr.readyState == xhr.DONE){
if(xhr.status == 200) {
var jsonData = JSON.parse(xhr.responseText);
for(var index in jsonData.data.posts) {
listModel.append({
"text": jsonData.data.posts[index].text,
"description": jsonData.data.posts[index].description});
alert(jsonData.data.posts[index].text);
}
}
}
}
xhr.send();
}QML代码:
import QtQuick 1.1
import "try.js" as JS
Item {
id:root
width: 360
height: 640
Component.onCompleted: JS.load()
ListModel {
id:listModel
}
ListView {
id:view
anchors.fill:parent
model : listModel
delegate: Rectangle {
width:parent.width
height:80
Text {
anchors.centerIn:parent
text: text
}
}
}
}注意:使用Necessitas在Android上部署Qt应用程序!
注释2:来自我的服务器的JSON数据的格式类似于上面的示例链接中给出的格式。
发布于 2014-01-14 08:01:32
我几乎成功了。唯一的问题是,如果有关模型已经有一个元素,当我们要做append时,它将有两个元素,但是只有第一个元素将被重绘。可能我错过了文档里的东西。
Ninja,我可以建议您避免使用与命名委托属性相同的方式命名角色,因为text: text可能会工作,但是在text: "a"+text中,当您期望引用模型的角色名时,第二个text将被引用到第一个text。
所以,更好的代码是
main.qml
import QtQuick 2.1
import "try.js" as JS
Rectangle {
id:root
width: 640
height: 480
ListModel {
id:listModel
ListElement { title: "a" }
}
ListView {
id:view
width: 600
height: 500
model : listModel
orientation: ListView.Vertical
delegate: Rectangle {
width: 100
height: 20
color: "yellow"
Text {
text: title
color: "black"
}
Component.onCompleted: console.log("rectangle created ", title, index);
}
}
Component.onCompleted: JS.load()
}try.js
function load() {
listModel.clear();
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://echo.jsontest.com/key/value/otherkey/othervalue", true);
xhr.onreadystatechange = function() {
if(xhr.readyState == xhr.DONE) {
if(xhr.status == 200) {
var jsonData = JSON.parse(xhr.responseText);
console.log(listModel);
listModel.append({
"title": "text1",
"description": "desc1"
});
console.log("ANswer gotten", jsonData);
}
}
}
xhr.send();
}https://stackoverflow.com/questions/21090652
复制相似问题