qml ajax 擷取json資料樣本

來源:互聯網
上載者:User

標籤: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資料樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.