Cómo accedo a servicios web JSON desde QML
-
Quisiera saber que es necesario para acceder a datos web JSON, concretamente a la API de
Community Radio Browser: http://www.radio-browser.info/webservicePor ejemplo, esta llamada:
http://www.radio-browser.info/webservice/json/stations/bytag/soulHasta ahora tenía el siguiente ejemplo de acceso a la API de Flickr del libro Qt 5 Cadaques (https://qmlbook.github.io/en/ch11/index.html#flickr-calls), pero no funciona para otros servicios:
import QtQuick 2.5
Rectangle {
width: 320
height: 480
ListView {
id: view
anchors.fill: parent
delegate: Thumbnail {
width: view.width
text: modelData.title
iconSource: modelData.media.m
}
}function request() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) { print('HEADERS_RECEIVED') } else if(xhr.readyState === XMLHttpRequest.DONE) { print('DONE') var json = JSON.parse(xhr.responseText.toString()) view.model = json.items } } xhr.open("GET", "http://api.flickr.com/services/feeds/photos_public.gne?format=json&nojsoncallback=1&tags=munich"); xhr.send(); } Component.onCompleted: { request() }
}
¿Depende de si la respuesta JSON retorna o no un callback?
-
@qtuser01 Hola,
prueba este codigo:
import QtQuick 2.5
Rectangle {
width: 320
height: 480
ListModel{
id:mimodel
}ListView { id: view anchors.fill: parent model: mimodel delegate: Text { width: view.width height: 25 text: name } } function request() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) { print('HEADERS_RECEIVED') } else if(xhr.readyState === XMLHttpRequest.DONE) { print('DONE') var json = JSON.parse(xhr.responseText.toString()) mimodel.clear(); for(var i = 0,len=json.length;i<len;i++){ mimodel.append(json[i]); } } } xhr.open("GET", "http://www.radio-browser.info/webservice/json/stations/bytag/soul"); xhr.send(); } Component.onCompleted: { request() }
}
suerte!