模块化 JS Ajax 请求

现在有一个需求,点击 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;">&nbsp;</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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值