標籤:style blog http ar io color os sp for
依賴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: 60011 height: 40012 spacing: 1013 columns: 214 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 // POST13 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 }
qml ajax 擷取json資料樣本