这两天想研究下ajax,看到《head first ajax》这本书,可惜里面用的是php,服务器有关的技术我只懂django,所以就用他了。

    用户注册这种东西很常见,当输入用户名的时候应该可以立即检查这个用户名是否被注册了,这就是hf这本书第二章讲的东西。由于不想用数据库(没必要啊,主要是练习前端),所以数据存储部分选择xml或者json,xml还是很麻烦的,json看起来清爽多了,就用json了。

    自定义的数据格式,对比xml于json:

1 <?xml version="1.0" encoding="UTF-8"?>  
2 <usres>
3     <user>
4         <name>duoduo</name>    
5     </user>
6 </usres>
 1 {
 2     "users": [
 3         {
 4             "name": "duoduo"
 5         }, 
 6         {
 7             "name": "lili"
 8         }
 9     ]
10 }

 


    json的格式说明可见:http://json.org/json-zh.html

    完整的实验代码


View Code
 1 import json
 2 import os
 3 path = os.path.join('.','user.json')
 4 
 5 def get_json_from_file(path):
 6     f = file(path)
 7     try:
 8         j = json.load(f)        
 9     finally:
10         f.close()
11         return j
12     
13 def write_to_file(s,path):
14     f = file(path,'w')
15     try:
16         f.write(s)
17     finally:
18         f.close()
19 
20 def is_register(user_name,uers_json):
21     users = uers_json['users']
22     for user in users:
23         if user['name'] == user_name:
24             return True
25     return False
26 
27 def add_user(user_name,user_json,path):
28     users = user_json['users']
29     users.append(dict(name=user_name))
30     write_to_file(json.dumps(user_json),path)
31 
32 def register(user_name):
33     path = os.path.join('.','user.json')
34     users_info = get_json_from_file(path)
35     if not is_register(user_name,users_info):
36         add_user(user_name,users_info,path)
37         return True
38     return False

 


    get_json_from_file是从一个json格式的文件中获得对应的python对象,json的{}对应python的字典,[]对应list。

    is_register判断用户是否注册。

    add_user将未注册的用户进行注册,并通过write_to_file将新的数据写回到文件夹。

    python的json库中有load,dump于loads,dumps,带s的操作的对象都是与字符串类似的对象,不带s的一组则操作与文件类似的对象。

    最后是操作的演示:


 

posted on 2013-02-26 14:33  duoduo3_69  阅读(1283)  评论(0编辑  收藏  举报