为什么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