Zhong

Keep thinking. Keep moving.

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

  最近微信公众帐号要扩展做一个签到系统,签到结果在一个网页上实时更新,即页面局部刷新。我想用Ajax来实现,之前公众帐号是用的Django搭的,我查找了Django的官方文档,没有封装Ajax。网上有各种方法,眼花缭乱。之前在图书馆借了本书《Django Web 开发指南》里面,有Ajax的实例,但是旧版本的Django,代码没法运行,但是里面倒是提供一种方法——把数据翻译成JSON格式,然后按照我们的格式返回字符串结果,在写到HttpResponse里去。我借鉴了其中的方法。查了Django的官方文档,我修改了书中的代码,可以正常运行。自己也写了一个demo

  我的直接简单地在views.py把数据存在一个list中,然后用JSON格式储存,写到HttpResponse中

 1 from django.http import HttpResponse
 2 from django.shortcuts import render_to_response
 3 import json
 4 
 5 def data(request, id):
 6     rlist = [['Jack', 'Chinese'], ['Mike', 'English'], ['Bob', 'Math'], ['Frank', 'Art'], ['Lucy', 'Music']]
 7     rlist2 = []
 8     rlist2.append({"name" : rlist[int(id)][0], "subject" : rlist[int(id)][1]})
 9     rjson = json.dumps(rlist2)
10     response = HttpResponse()
11     response['Content-Type'] = "text/javascript"
12     response.write(rjson)
13     return response
14     
15 def update(request):
16     return render_to_response('update.html')

 

   url.py中有两个地址,一个是展示页面,一个是数据保存地址

1 from django.conf.urls import patterns,  url
2 from AjaxTest.views import data, update
3 
4 urlpatterns = patterns('',
5     url(r'^data/(?P<id>\d+)/$', data),
6     url(r'^update/', update)
7 )

  访问http://127.0.0.1:8000/data/id/, id是数字,可获取对应JSON数据

 

 

 

  这一步很关键,接下来我们编写和这个API视图交互Javascript,并用它来响应页面。我用jQuery中的ajax,每隔3秒执行一次 update() 函数,用jQuery的 getJSON 方法,发送URL请求,解析结果,这样完成Ajax,Javascript代码如下

 

 1 function update(id) {
 2    $.getJSON("/data/" + id + "/",function(data) {
 3       $.each(data, function(){
 4          $("#content").html('<p>' + this.name + ' is a ' + this.subject + ' teacher.</p>');
 5          });
 6    });
 7 }
 8 function timeDown(limit, i) {
 9    limit--;
10    if (i > 4) {
11        i = 0;
12    }
13    if (limit < 0) {
14        limit = 3;
15        update(i);
16        i++;
17    }
18    $('#time').text(limit + '秒后刷新');
19        setTimeout(function() {
20            timeDown(limit, i);
21             }, 1000)
22 }
23            
24 $(document).ready(function() {
25    timeDown(3, 0)
26 })

   html页面代码

 1 <html>
 2  <head>
 3    <title>Ajax Test</title>
 4    <script src="http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
 5    <script type="text/javascript" language="javascript">
 6            function update(id) {
 7                $.getJSON("/data/" + id + "/",function(data) {
 8                 $.each(data, function(){
 9                     $("#content").html('<p>' + this.name + ' is a ' + this.subject + ' teacher.</p>');
10                 });
11                });
12            }
13            function timeDown(limit, i) {
14                limit--;
15                if (i > 4) {
16                    i = 0;
17                }
18                if (limit < 0) {
19                    limit = 3;
20                    update(i);
21                    i++;
22                }
23                $('#time').text(limit + '秒后刷新');
24                setTimeout(function() {
25                    timeDown(limit, i);
26                }, 1000)
27            }
28            
29            $(document).ready(function() {
30                timeDown(3, 0)
31         })
32    </script>
33  </head>
34  <body>
35    <h1>Ajax Test</h1>
36    <p id="time"></p>
37    <div id="content"></div> 
38  </body>
39 </html>

 

  运行服务器,访问http://127.0.0.1:8000/update/,每隔3秒刷新一次更新内容,如下图

  

  Demo代码下载地址

  https://files.cnblogs.com/stwzhong/AjaxTest.zip

  《Django Web 开发指南》书上修改后代码下载地址

  https://files.cnblogs.com/stwzhong/Liveblog.zip

   

posted on 2014-04-07 19:23  stwzhong  阅读(6939)  评论(0编辑  收藏  举报