不使用Backbone自带的sync功能,自己写一套Ajax与后台交互。
var Ajax = { fetch: function(Model,func){ var fetch_data; $.ajax({ type: "POST",url: Global.url,data: {csrfmiddlewaretoken: Global.csrf,ajax_cmd: "fetch"},success: function(data) { fetch_data = JSON.parse(data); if (fetch_data.length === undefined){ alert("fetch_data.length undefined"); return; } alert(fetch_data.length); for (var i = 0; i < fetch_data.length; i++){ var model = new Model(fetch_data[i].fields); func(model); } },error: function(xhr,textStatus,errorThrown) { alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText); } }); return fetch_data; },add: function(model){ var json_string = JSON.stringify(model); alert(json_string); $.ajax({ type: "POST",ajax_cmd: "add",json_data: json_string,},success: function(status) { if (status == 'succ'){ return; } else{ alert("add: server return fail"); } },errorThrown) { alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText); } }); },del: function(model){ var json_string = JSON.stringify(model); alert(json_string); $.ajax({ type: "POST",ajax_cmd: "delete",success: function(status) { if (status == 'succ'){ return; } else{ alert("del: server return fail"); } },errorThrown) { alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText); } }); },};
Ajax对象有三个方法:
(1)fetch
入参:Model,backbone的Model对象,将服务器返回的数据生成Model对象。
func,Ajax从服务器获得数据之后的回调函数,一般地功能是将生成的Model对象显示在视图上。
(2)add
入参:model,backbone Model实例。
原理:将Model转成JSON格式,POST到服务器,服务器解析JSON数据,存储之。
(3)del
入参:model,backbone Model实例。
原理:将Model转成JSON格式,POST到服务器,服务器解析JSON数据,查找此对象,如果找到就删除
update方法暂无需求,,,
这里用到一个Global对象,定义如下:
var Global = { url: "/ajax/",csrf: document.getElementsByName('csrfmiddlewaretoken')[0].value,};
说明:url,服务器端响应Ajax请求的地址;
csrf,django安全需要。
服务器端的代码:
models.py
class Message(models.Model): msg = models.CharField(max_length=300) time = models.DateTimeField(auto_now=True) msg_user = models.ForeignKey(User) def __unicode__(self): return self.msg
views.py
def ajax(request): if request.is_ajax(): if request.method == "POST": ajax_cmd = request.POST['ajax_cmd'] print ajax_cmd if 'add' == ajax_cmd: json_data = request.POST['json_data'] decode_data = json.loads(json_data) print type(decode_data) print decode_data user = User.objects.get(pk=1) msg = Message(msg=decode_data['msg'],msg_user=user) msg.save() return HttpResponse('succ') elif 'fetch' == ajax_cmd: data = serializers.serialize('json',Message.objects.all(),fields=('msg','time')) print data return HttpResponse(data) elif 'delete' == ajax_cmd: json_data = request.POST['json_data'] decode_data = json.loads(json_data) print decode_data['msg'] print decode_data['time'] msg = Message.objects.filter(msg=decode_data['msg'],time=decode_data['time'])[0] msg.delete() return HttpResponse('succ') return else: raise Http404
不更新了,改学angular.js + node.js!!!