qt qml ajax 获取 json 天气数据示例
依赖ajax.js类库,以下代码很简单的实现了获取天气json数据并展示的任务
【TestAjax.qml】
1 import QtQuick 2.0 2 import "ajax.js" as Ajax 3 4 5 /** 6 测试用ajax 获取 json 数据 7 更复杂的ajax调用请查看 qml/network/ 相关示例 8 */ 9 Grid{ 10 width: 600 11 height: 400 12 spacing: 10 13 columns: 2 14 15 Text {text: 'city:'} 16 Text {id:city; text:' '} 17 18 Text {text: 'date:'} 19 Text {id:date; text:' '} 20 21 Text {text: 'temp:'} 22 Text {id:temp1; text:' '} 23 24 Component.onCompleted: { 25 // 中国天气网实况天气接口(可用) 26 Ajax.get("http://www.weather.com.cn/data/sk/101010100.html", 27 function(result, json){ 28 city.text = json.weatherinfo.city; 29 date.text = json.weatherinfo.time; 30 temp1.text = json.weatherinfo.temp; 31 } 32 ); 33 34 /* 35 // 中华万年历的当天及预告天气接口(可用) 36 Ajax.get("http://wthrcdn.etouch.cn/weather_mini?city=%E5%8C%97%E4%BA%AC", 37 function(result, json){ 38 city.text = json.data.city; 39 date.text = json.data.forecast[0].date; 40 temp1.text = json.data.wendu; 41 } 42 ); 43 */ 44 45 /* 46 // 中国天气网当天及预告天气接口(接口挂了) 47 Ajax.get("http://m.weather.com.cn/data/101010100.html", 48 function(result, json){ 49 city.text = json.weatherinfo.city; 50 date.text = json.weatherinfo.date_y; 51 temp1.text = json.weatherinfo.temp1; 52 } 53 ); 54 */ 55 } 56 }
【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 }
转载请注明出处:http://surfsky.cnblogs.com