上回玩到Tastypie与jQuery交互,那么现在接着玩玩Tastypie与Backbone.js交互

先把上篇的template文件:D:\project\tastypie\mysite\blog\templates\blog\index.html改改,添加了backbone的相关依赖文件,代码如下[增、删、改、查]:

一、GET id为1的blog文章出来:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title> </head>
<body>
<script type="text/javascript" src="/static/js/underscore-min.js"></script>
<script type="text/javascript" src="/static/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/static/js/json2.js"></script>
<script type="text/javascript" src="/static/js/backbone-min.js"></script>
<script>
$(function () {
var blogModel = Backbone.Model.extend({
urlRoot: '/api/v1/entry/',
defaults: {
user: '/api/v1/user/2/',
pub_date: '2015-01-29T11:07:30',
title: '',
body: '',
slug: ''
}
});
var blog = new blogModel({ id: 1 });
blog.fetch({
success: function(blog){
console.log(blog.toJSON());
}
}); });
</script>
</body>
</html>

打开Chrome按个F12调出log来看看结果查询内容成功,返回了一个条json记录。

二、POST一条blog

    <script>
$(function () {
var blogModel = Backbone.Model.extend({
urlRoot: '/api/v1/entry/',
defaults: {
user: '/api/v1/user/2/',
pub_date: '2015-01-29T11:07:30',
title: '',
body: '',
slug: ''
}
});
var blogDetails = {
user: '/api/v1/user/2/',
pub_date: '2015-01-29T11:07:30',
title: 'blackbone test4',
body: 'blackbone test4',
slug: 'another-post4'
};
blog.save(blogDetails, {
success: function (blog) {
console.log(blog.toJSON());
},
error: function(e){
alert("error!")
}
})
});
</script>

打开Chrome按个F12调出log来看看结果Post内容成功,返回了一个条json记录。

三、通过PUT方式update一条id为1的blog

    <script>
$(function () {
var blogModel = Backbone.Model.extend({
urlRoot: '/api/v1/entry/',
defaults: {
user: '/api/v1/user/2/',
pub_date: '2015-01-29T11:07:30',
title: '',
body: '',
slug: ''
}
});
var blog = new blogModel({ id: 1 }); blog.save({user:'/api/v1/user/2/',pub_date: '2015-01-29T11:07:30',title:'Haha!',body: 'blackbone test4',slug: 'another-post4'},{
success: function(blog){
console.log(blog.toJSON());
}
}); });
</script>

打开Chrome按个F12调出log来看看结果更新内容成功,返回了一个条json记录。

四、通过DELETE方式删除一条id为1的blog

   <script>
$(function () {
var blogModel = Backbone.Model.extend({
urlRoot: '/api/v1/entry/',
defaults: {
user: '/api/v1/user/2/',
pub_date: '2015-01-29T11:07:30',
title: '',
body: '',
slug: ''
}
});
var blog = new blogModel({ id: 1 });
blog.destroy({
success: function () {
console.log('Destroy!');
} });
});
</script>

浏览器打开http://localhost:8000/api/v1/entry/1/记录无内容,已删除成功

04-28 06:04