使用Python的Django框架結(jié)合jQuery實(shí)現(xiàn)AJAX購物車頁面
Django中集成jquery
首先,靜態(tài)的資源通常放入static文件夾中:
static/ css/ djquery.css samples/ hello.css js/ jquery-1.7.1.min.js samples/ hello.js
其中css和js都按照應(yīng)用名稱(這里是samples)劃分文件夾,如果文件較多,還可以再劃分子文件夾。
Django通常使用模板來展現(xiàn)html,而且我們通常使用繼承的模板,所以需要將共用的元素,比如全局的css,對jquery.js的引入等,寫到base模板中,而將具體頁面的元素放到具體的模板中。這就牽涉到如何嵌套的問題。看下面的例子:
base.html
<html> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>{% block title %} 標(biāo)題 {% endblock %}</title> <link href="css/djquery.css" rel="stylesheet"> {% block styles %}<!--custom styles-->{% endblock %} </head> <body> <div id="container"> {% block content %}內(nèi)容{% endblock %} </div> </body> <script language="JavaScript" type="text/javascript" src="/static/js/jquery-1.7.1.min.js"></script> {% block scripts %} <!--custom scripts--> {% endblock %} </html>
samples/hello.html
{% extends "base.html" %} {% block title %} hello, djquery! {% endblock %} {% block styles %} {% endblock %} {% block content %} <div><input type="button" id="myField" value="Click me!"/></div> {% endblock %} {% block scripts %} <script language="JavaScript" type="text/javascript" src="/static/js/djquery/hello.js"></script> {% endblock %}
Hello, Djquery!
有了上述的“框架”,我們就可以很容易的驗(yàn)證一下我們的想法,比如這個“Hello Djquery”。只需要在urls.py中配置一下:
(r'hello/$', 'django.views.generic.simple.direct_to_template', {'template':'samples/hello.html'}),
其中direct_to_template是django提供的一個通用視圖。
AJAX實(shí)現(xiàn)示例
我們來看一個購物車的例子。假設(shè)現(xiàn)在我們有一個使用json格式的RESTful API,可以實(shí)現(xiàn)這樣的功能了:為了避免在產(chǎn)品列表和購物車之間來回切換,需要在產(chǎn)品列表界面顯示購物車,并且通過ajax的方式不刷新界面就更新購物車的顯示內(nèi)容,利用我們上面在Django中集成的jQuery。
1.嵌入購物車界面
為了實(shí)現(xiàn)如下圖所示的嵌入購物車的產(chǎn)品目錄界面,我們需要做兩件事情:
(1)修改模板:
depot/templates/depotapp/store.html:
{% extends "base.html" %} {% block title %} 產(chǎn)品目錄 {% endblock %} {% block pagename %} 產(chǎn)品目錄 {% endblock %} {% block content %} <div class="row"> <div class="span10"> {% for item in products %} <div class="row" style="padding-top:10"> <div class="span3 media-grid"> <a href="#"> <img class="thumbnail" src="{{item.image_url}}" alt=""> </a> </div> <div class="span6"> <h3>{{item.title}}</h3> <br/> {{item.description}} <br/> <br/> <br/> <div class="row"> <div class="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div> <div class="span"><a class="btn primary" href="{% url depotapp.views.add_to_cart item.id %}">加入購物車</a></div> </div> </div> </div> <div class="page-header"> </div> {% endfor %} </div><!--span10--> <div class="span4"> <h5>我的購物車</h5><br/> <table class="condensed-table"> <tbody> {% for item in cart.items %} <tr> <th>{{item.quantity}}x</th> <td>{{item.product.title}}</td> <td>¥{% widthratio item.quantity 1 item.unit_price %} </td> </tr> {% endfor %} <tr> <td></td> <th>總計(jì):</th> <th>¥{{cart.total_price|floatformat:"2"}}</th> </tr> </tbody> </table> <a class="btn danger" href="{% url depotapp.views.clean_cart %}">清空</a> <a class="btn success" href="#">結(jié)算</a> </div><!--span4--> {% endblock %}
(2)在depotapp/views.py中的store_view視圖函數(shù)中增加一行:
cart = request.session.get("cart",None)
就可以顯示出如上的界面了。
2.編寫javascript實(shí)現(xiàn)ajax
現(xiàn)在讓我們來通過ajax請求后臺服務(wù)。當(dāng)然首選要實(shí)現(xiàn)后臺服務(wù)。關(guān)于“加入購物車”,我們需要的服務(wù)是這樣定義的:
url: http://localhost:8000/depotapp/API/cart/items/post
post數(shù)據(jù): product = product_id
處理過程: 根據(jù)product_id,將product加入購物車
返回:購物車中的所有條目
這個API的定義似乎不那么RESTful,但是暫且不去管它。實(shí)現(xiàn)這個服務(wù)需要為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來測試服務(wù)接口(使用Firebug調(diào)試是非常方便的辦法):
如同你看到的那樣,我們的接口定義不是完全RESTful,在生成的表單中,我們只需要選擇Product,不用管另外的兩個表單項(xiàng),POST之后就可以從之前實(shí)現(xiàn)的購物車界面中看到新增加的產(chǎn)品項(xiàng)了。
服務(wù)接口測試通過,就可以在界面中通過ajax調(diào)用了。jquery對ajax提供了豐富的支持,為了方便使用jquery的selector,先要對html進(jìn)行改造。將上面實(shí)現(xiàn)的depot/templates/depotapp/store.html中,迭代產(chǎn)品的部分改成如下的樣子:
{% 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>標(biāo)簽,增加productid屬性,并將href改為“#”。這樣我們就可以很方便的為其添加事件:
//store.html on ready $('a.btn[productid]').bind("click",function(){ alert($(this).attr("productid")); } );
這段代碼實(shí)現(xiàn)的功能是:對于所有的標(biāo)簽<a>,如果class包括“btn”,并且擁有“productid”屬性的元素,添加click事件,彈出對話框顯示其“productid”屬性值。
打開產(chǎn)品清單界面測試一下,能夠正確彈出產(chǎn)品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接口的返回值,即現(xiàn)有購物車中的條目列表。
最后,要根據(jù)返回的數(shù)據(jù)更改界面上的購物車顯示。這里為了方便也對html進(jìn)行了改造。整個完成的depot/templates/depotapp/store.html如下:
{% extends "base.html" %} {% block title %} 產(chǎn)品目錄 {% endblock %} {% block pagename %} 產(chǎn)品目錄 {% 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>總計(jì):</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="#">結(jié)算</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函數(shù),根據(jù)參數(shù)”重繪“購物車界面。在$(document).ready部分,首先調(diào)用前面實(shí)現(xiàn)的API顯示購物車,這樣我們在模板中就可以去掉原來實(shí)現(xiàn)的”購物車“,改成javascript的方式。
然后為每個”加入購物車“按鈕添加點(diǎn)擊事件,調(diào)用本節(jié)開始部分實(shí)現(xiàn)的接口,根據(jù)返回的最新條目數(shù)據(jù)調(diào)用refreshCart函數(shù)重繪購物車。
上面的模板中,javascript的部分劃分成了兩個block:{% block js %}用于嵌入具體頁面(相對應(yīng)父模板)的js函數(shù);{% block on_ready %}用于嵌入具體頁面的$(document).ready處理。結(jié)合base.html中定義的block,可以使組合在一起的具體頁面和模板頁面符合Unobtrusive JavaScript 。這樣做應(yīng)該是Django+jquery實(shí)現(xiàn)ajax的最佳實(shí)踐。
相關(guān)文章
利用python中pymysql操作MySQL數(shù)據(jù)庫的新手指南
PyMySQL是在Python3.x版本中用于連接MySQL服務(wù)器的一個庫,Python2中是使用mysqldb,這篇文章主要給大家介紹了關(guān)于利用python中pymysql操作MySQL數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2021-09-09Python實(shí)現(xiàn)連接MySQL數(shù)據(jù)庫的常見方法總結(jié)
這篇文章主要為大家介紹了兩種Python中用來連接 MySQL 數(shù)據(jù)庫的方法,并且針對這兩種方法,我們還將對代碼進(jìn)行封裝和優(yōu)化,提高程序的可讀性和健壯性,需要的可以收藏一下2023-05-05django 發(fā)送手機(jī)驗(yàn)證碼的示例代碼
本篇文章主要介紹了django 發(fā)送手機(jī)驗(yàn)證碼的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04100行Python代碼實(shí)現(xiàn)每天不同時間段定時給女友發(fā)消息
這篇文章主要介紹了100行Python代碼,每天不同時間段定時給女友發(fā)消息,本文給出了實(shí)現(xiàn)思路,代碼簡單易懂非常不錯,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09Python雙端隊(duì)列deque的實(shí)現(xiàn)
雙端隊(duì)列deque支持從任意一端增加和刪除元素。本文詳細(xì)的介紹了Python雙端隊(duì)列deque的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06