當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
模块化 JS Ajax 请求
生活随笔
收集整理的這篇文章主要介紹了
模块化 JS Ajax 请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
現在有一個需求,點擊 Button需要調用一個函數獲取 JSON 數據傳給 artTemplate 模板渲染生成頁面,所以需要在這個函數中封裝原生的 JS Ajax,同時重新渲染頁面。
Arttemplate 模板
<div id="topic_content" class="topic"></div><script id="topic_template" type="text/html">{{if isAdmin}}<ul>{{each list as value}}<li> <a href= {{value.url}}> {{ value.title }} </a> <span style="font-size:20px;"> </span> {{ value.followers }}</li>{{/each}}</ul>{{/if}}</script>封裝原生 Ajax
<script>function getTopTopicsByDay(day){function success(text) {var js_obj_of_list_in_json = JSON.parse(text);var data = {title: 'topic',isAdmin: true,list: js_obj_of_list_in_json.topics };// list 應該是一個數組給 template 渲染,不是一個字符串。var html = template('topic_template', data);document.getElementById('topic_content').innerHTML = html;}function fail(code) {return;}var request = new XMLHttpRequest();request.onreadystatechange = function () {if (request.readyState === 4) { // 成功完成// 判斷響應結果:if (request.status === 200) {// 成功,通過responseText拿到響應的文本:return success(request.responseText);} else {// 失敗,根據響應碼判斷失敗原因:return fail(request.status);}} else {// HTTP請求還在繼續...}}// 發送請求:request.open('GET', 'http://202.201.13.172:5000/toptopic/api/topics');request.send();}</script>返回的 JSON 數據
{"topics": [{"ask_time": "Thu, 10 Dec 2015 07:27:01 GMT", "followers": 1275, "question_id": "38369521", "title": "\u5982\u4f55\u7ed9\u81ea\u5df1\u5404\u79cd\u5e10\u53f7\u7f16\u4e00\u4e2a\u5b89\u5168\u53c8\u4e0d\u4f1a\u5fd8\u8bb0\u7684\u5bc6\u7801\uff1f", "url": "https://www.zhihu.com/question/38369521"}, {"ask_time": "Wed, 09 Dec 2015 15:23:18 GMT", "followers": 1256, "question_id": "38341320", "title": "\u5728\u77e5\u4e4e\u300c\u6587\u5b66\u300d\u9886\u57df\u6709\u54ea\u4e9b\u503c\u5f97\u5173\u6ce8\u7684\u7528\u6237\uff1f", "url": "https://www.zhihu.com/question/38341320"} ] }參考
http://www.oschina.net/code/snippet_932545_46223
http://aui.github.io/artTemplate/#%E4%BD%BF%E7%94%A8%E9%A2%84%E7%BC%96%E8%AF%91
轉載于:https://my.oschina.net/lvyi/blog/543155
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的模块化 JS Ajax 请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Windows]_[0基础]_[使用命
- 下一篇: 【cocos2d-js官方文档】二十五、