Django实战(17):ajax !

现在让我们来通过ajax请求后台服务。当然首选要实现后台服务。关于“加入购物车”,我们需要的服务是这样定义的:

  1. url:    http://localhost:8000/depotapp/API/cart/items/post
  2. post数据: product = product_id
  3. 处理过程: 根据product_id,将product加入购物车
  4. 返回:购物车中的所有条目

这个API的定义似乎不那么RESTful,但是暂且不去管它。实现这个服务需要为RESTful web service(depotapp/views.py中的RESTforCart类)增加一个方法:

 

    def post(self, request, *args, **kwargs):
    print request.POST['product']
    product = Product.objects.get(id=request.POST['product'])
    cart = request.session['cart']
    cart.add_product(product)
    request.session['cart'] = cart
    return request.session['cart'].items

可以通过http://localhost:8000/depotapp/API/cart/items/post来测试服务接口(使用Firebug调试是非常方便的办法):

 

如同你看到的那样,我们的接口定义不是完全RESTful,在生成的表单中,我们只需要选择Product,不用管另外的两个表单项,POST之后就可以从之前实现的购物车界面中看到新增加的产品项了。

服务接口测试通过,就可以在界面中通过ajax调用了。jquery对ajax提供了丰富的支持,为了方便使用jquery的selector,先要对html进行改造。将上一节实现的depot/templates/depotapp/store.html中,迭代产品的部分改成如下的样子:

    {% for item in products %}
    <divclass="row"style="padding-top:10">
    <divclass="span3 media-grid">
    <ahref="#">
    <imgclass="thumbnail"src="{{item.image_url}}"alt="">
    </a>
    </div>
    <divclass="span6">
    <h3>{{item.title}}</h3>
    <br/>
    {{item.description}}
    <br/>
    <br/>
    <br/>
    <divclass="row">
    <divclass="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div>
    <divclass="span"><aclass="btn primary"productid="{{item.id}}"href="#">加入购物车</a></div>
    </div>
    </div>
    </div>
    <divclass="page-header">
    </div>
    {% endfor %}

其中主要更改了“加入购物车”的<a>标签,增加productid属性,并将href改为“#”。这样我们就可以很方便的为其添加事件:

    //store.html on ready
    $('a.btn[productid]').bind("click",function(){
    alert($(this).attr("productid"));
    }
    );

这段代码实现的功能是:对于所有的标签<a>,如果class包括“btn”,并且拥有“productid”属性的元素,添加click事件,弹出对话框显示其“productid”属性值。

 

打开产品清单界面测试一下,能够正确弹出产品ID,然后就可以编写ajax的处理了。在这里我们使用jquery.post()方法,jquery.post()是jquery.ajax的简化写法,如下:

 

    //store.html on ready
    $('a.btn[productid]').bind("click",function(){
    var product_id=$(this).attr("productid");
    //alert(product_id);
    $.post("/depotapp/API/cart/items/post",
    {product:product_id},
    function(data){
    alert(data);
    }
    );
    }
    );

 

弹出对话框显示的data就是前面定义的API接口的返回值,即现有购物车中的条目列表。

 

最后,要根据返回的数据更改界面上的购物车显示。这里为了方便也对html进行了改造。整个完成的depot/templates/depotapp/store.html如下:

 

    {% extends "base.html" %}
    {% block title %} 产品目录 {% endblock %}
    {% block pagename %} 产品目录 {% endblock %}
    {% block content %}
    <divclass="row">
    <divclass="span10">
    {% for item in products %}
    <divclass="row"style="padding-top:10">
    <divclass="span3 media-grid">
    <ahref="#">
    <imgclass="thumbnail"src="{{item.image_url}}"alt="">
    </a>
    </div>
    <divclass="span6">
    <h3>{{item.title}}</h3>
    <br/>
    {{item.description}}
    <br/>
    <br/>
    <br/>
    <divclass="row">
    <divclass="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div>
    <divclass="span"><aclass="btn primary"productid="{{item.id}}"href="#">加入购物车</a></div>
    </div>
    </div>
    </div>
    <divclass="page-header">
    </div>
    {% endfor %}
    </div><!--span10-->
    <divclass="span4">
    <h5>我的购物车</h5><br/>
    <tableid="tabCart"class="condensed-table">
    <tbodyid="items">
    </tbody>
    <tfoot>
    <tr>
    <td></td>
    <th>总计:</th>
    <tdid="totalprice">¥{{cart.total_price|floatformat:"2"}}</td>
    </tr>
    </tfoot>
    </table>
    <aclass="btn danger"href="{% url depotapp.views.clean_cart %}">清空</a>
    <aclass="btn success"href="#">结算</a>
    </div><!--span4-->
    {% endblock %}
    {% block js %}
    <!--js from store.html-->
    <script>
    function refreshCart(items){
    total = 0;
    var tbody = $('tbody#items')[0];
    tbody.innerHTML = "";
    for(var i=0;i<items.length;i++){
    total+=items[i].quantity*items[i].unit_price;
    $('table#tabCart').append('<tr><td>'+items[i].quantity+'x</td>'+
    '<td>'+items[i].product+'</td><td>¥'+items[i].unit_price+
    '</td></tr>');
    }
    $('#totalprice')[0].innerHTML = '$'+total;
    }
    </script>
    {% endblock %}
    {% block on_ready %}
    //store.html on ready
    $.getJSON('/depotapp/API/cart/items/',refreshCart);
    $('a.btn[productid]').bind("click",function(){
    var product_id=$(this).attr("productid");
    //alert(product_id);
    $.post("/depotapp/API/cart/items/post",{product:product_id},refreshCart);
    }
    );
    {% endblock %}

定义了一个refreshCart函数,根据参数”重绘“购物车界面。在$(document).ready部分,首先调用前面实现的API显示购物车,这样我们在模板中就可以去掉原来实现的”购物车“,改成javascript的方式。

然后为每个”加入购物车“按钮添加点击事件,调用本节开始部分实现的接口,根据返回的最新条目数据调用refreshCart函数重绘购物车。

上面的模板中,javascript的部分划分成了两个block:{% block js %}用于嵌入具体页面(相对应父模板)的js函数;{% block on_ready %}用于嵌入具体页面的$(document).ready处理。结合base.html中定义的block,可以使组合在一起的具体页面和模板页面符合Unobtrusive JavaScript 。这样做应该是Django+jquery实现ajax的最佳实践。

转载于:https://www.cnblogs.com/wuxl360/p/5787913.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值