国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

使用Python的Django框架結合jQuery實現AJAX購物車頁面

2020-01-04 17:33:23
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了使用Python的Django框架結合jQuery實現AJAX購物車頁面的方法,示例基于Django中構建好的JSON格式的RESTful API需要的朋友可以參考下
 

Django中集成jquery
首先,靜態的資源通常放入static文件夾中:

static/  css/    djquery.css    samples/      hello.css  js/    jquery-1.7.1.min.js    samples/      hello.js

其中css和js都按照應用名稱(這里是samples)劃分文件夾,如果文件較多,還可以再劃分子文件夾。

Django通常使用模板來展現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 %} 標題 {% endblock %}</title>  <link href="css/djquery.css" rel="stylesheet">{% block styles %}<!--custom styles-->{% endblock %} </head> <body>  <div id="container">{% block content %}內容{% 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!
有了上述的“框架”,我們就可以很容易的驗證一下我們的想法,比如這個“Hello Djquery”。只需要在urls.py中配置一下:

 

復制代碼代碼如下:

 

(r'hello/$', 'django.views.generic.simple.direct_to_template', {'template':'samples/hello.html'}),


其中direct_to_template是django提供的一個通用視圖。

 


AJAX實現示例
我們來看一個購物車的例子。假設現在我們有一個使用json格式的RESTful API,可以實現這樣的功能了:為了避免在產品列表和購物車之間來回切換,需要在產品列表界面顯示購物車,并且通過ajax的方式不刷新界面就更新購物車的顯示內容,利用我們上面在Django中集成的jQuery。
1.嵌入購物車界面
為了實現如下圖所示的嵌入購物車的產品目錄界面,我們需要做兩件事情:

Python,Django框架,jQuery,AJAX

(1)修改模板:

depot/templates/depotapp/store.html:

  {% extends "base.html" %}      {% block title %} 產品目錄 {% endblock %}   {% block pagename %} 產品目錄 {% 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}}"      </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>總計:</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="#">結算</a>     </div><!--span4-->   {% endblock %} 

(2)在depotapp/views.py中的store_view視圖函數中增加一行:

cart = request.session.get("cart",None)
就可以顯示出如上的界面了。

2.編寫javascript實現ajax
現在讓我們來通過ajax請求后臺服務。當然首選要實現后臺服務。關于“加入購物車”,我們需要的服務是這樣定義的:

url:    http://localhost:8000/depotapp/API/cart/items/post
post數據: product = product_id
處理過程: 根據product_id,將product加入購物車
返回:購物車中的所有條目
這個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'] = cartreturn request.session['cart'].items

可以通過http://localhost:8000/depotapp/API/cart/items/post來測試服務接口(使用Firebug調試是非常方便的辦法):

Python,Django框架,jQuery,AJAX

如同你看到的那樣,我們的接口定義不是完全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的最佳實踐。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宝清县| 前郭尔| 龙江县| 金寨县| 昂仁县| 桓台县| 中超| 塘沽区| 讷河市| 新田县| 广河县| 云浮市| 西吉县| 普安县| 门源| 喀什市| 龙岩市| 综艺| 赤壁市| 若尔盖县| 页游| 忻城县| 抚远县| 城口县| 镇雄县| 武山县| 莱州市| 独山县| 新闻| 江山市| 兖州市| 阜南县| 介休市| 嵩明县| 昭平县| 兴安盟| 赤壁市| 常宁市| 延川县| 营山县| 航空|