qml ajax 获取json数据示例
依赖ajax.js类库,以下代码很简单的实现了获取天气json数据并展示的任务
【TestAjax.qml】
1 import QtQuick 2.0 2 import QtQuick.Controls 1.2 3 import "ajax.js" as Ajax 4 5 6 /** 7 测试用ajax 获取 json 数据 8 */ 9 Grid{ 10 width: 600 11 height: 400 12 spacing: 10 13 columns: 2 14 15 Text {text: ‘city‘} 16 Text {id:city} 17 18 Text {text: ‘date‘} 19 Text {id:date} 20 21 Text {text: ‘temp‘} 22 Text {id:temp1} 23 24 Component.onCompleted: { 25 Ajax.get("http://m.weather.com.cn/atad/101230201.html", 26 function(result, json){ 27 city.text = json.weatherinfo.city; 28 date.text = json.weatherinfo.date_y; 29 temp1.text = json.weatherinfo.temp1; 30 } 31 ); 32 } 33 }
【ajax.js】
1 // GET 2 function get(url, success, failure) 3 { 4 var xhr = new XMLHttpRequest; 5 xhr.open("GET", url); 6 xhr.onreadystatechange = function() { 7 handleResponse(xhr, success, failure); 8 } 9 xhr.send(); 10 } 11 12 // POST 13 function post(url, arg, success, failure) 14 { 15 var xhr = new XMLHttpRequest; 16 xhr.open("POST", url); 17 xhr.setRequestHeader("Content-Length", arg.length); 18 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); //用POST的时候一定要有这句 19 xhr.onreadystatechange = function() { 20 handleResponse(xhr, success, failure); 21 } 22 xhr.send(arg); 23 } 24 25 26 27 // 处理返回值 28 function handleResponse(xhr, success, failure){ 29 if (xhr.readyState == XMLHttpRequest.DONE) { 30 if (xhr.status == 200){ 31 if (success != null && success != undefined) 32 { 33 var result = xhr.responseText; 34 try{ 35 success(result, JSON.parse(result)); 36 }catch(e){ 37 success(result, {}); 38 } 39 } 40 } 41 else{ 42 if (failure != null && failure != undefined) 43 failure(xhr.responseText, xhr.status); 44 } 45 } 46 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。