一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術(shù)及教程分享平臺!
分類導(dǎo)航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務(wù)器之家 - 腳本之家 - Python - 使用Python的Django框架結(jié)合jQuery實現(xiàn)AJAX購物車頁面

使用Python的Django框架結(jié)合jQuery實現(xiàn)AJAX購物車頁面

2020-08-19 09:51心內(nèi)求法 Python

這篇文章主要介紹了使用Python的Django框架結(jié)合jQuery實現(xiàn)AJAX購物車頁面的方法,示例基于Django中構(gòu)建好的JSON格式的RESTful API需要的朋友可以參考下

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

?
1
2
3
4
5
6
7
8
9
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{% 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中配置一下:

 

復(fù)制代碼 代碼如下:

 

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


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

 


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

使用Python的Django框架結(jié)合jQuery實現(xiàn)AJAX購物車頁面

(1)修改模板:

depot/templates/depotapp/store.html:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
{% 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>總計:</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實現(xiàn)ajax
現(xiàn)在讓我們來通過ajax請求后臺服務(wù)。當(dāng)然首選要實現(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,但是暫且不去管它。實現(xiàn)這個服務(wù)需要為RESTful web service(depotapp/views.py中的RESTforCart類)增加一個方法:

?
1
2
3
4
5
6
7
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)試是非常方便的辦法):

使用Python的Django框架結(jié)合jQuery實現(xiàn)AJAX購物車頁面

如同你看到的那樣,我們的接口定義不是完全RESTful,在生成的表單中,我們只需要選擇Product,不用管另外的兩個表單項,POST之后就可以從之前實現(xiàn)的購物車界面中看到新增加的產(chǎn)品項了。

服務(wù)接口測試通過,就可以在界面中通過ajax調(diào)用了。jquery對ajax提供了豐富的支持,為了方便使用jquery的selector,先要對html進行改造。將上面實現(xiàn)的depot/templates/depotapp/store.html中,迭代產(chǎn)品的部分改成如下的樣子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{% 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改為“#”。這樣我們就可以很方便的為其添加事件:

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

這段代碼實現(xiàn)的功能是:對于所有的標(biāo)簽<a>,如果class包括“btn”,并且擁有“productid”屬性的元素,添加click事件,彈出對話框顯示其“productid”屬性值。


打開產(chǎn)品清單界面測試一下,能夠正確彈出產(chǎn)品ID,然后就可以編寫ajax的處理了。在這里我們使用jquery.post()方法,jquery.post()是jquery.ajax的簡化寫法,如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
//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進行了改造。整個完成的depot/templates/depotapp/store.html如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
{% 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>總計:</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)用前面實現(xiàn)的API顯示購物車,這樣我們在模板中就可以去掉原來實現(xiàn)的”購物車“,改成javascript的方式。

然后為每個”加入購物車“按鈕添加點擊事件,調(diào)用本節(jié)開始部分實現(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實現(xiàn)ajax的最佳實踐。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产日韩欧美在线一二三四 | 色五婷婷| 小兰被扒开内裤露出p | 荡女人人爱 | 禁忌h1v1怀孕 | 99国产牛牛视频在线网站 | 高h短篇辣肉各种姿势bl | 人禽l交视频在线播放 视频 | 日本一区二区免费在线 | 海角社区在线视频 | 大东北chinesexxxx露脸 | 丝袜护士强制脚足取精 | 免费看一级a一片毛片 | 亚洲图片一区二区 | 国产精品刺激好大好爽视频 | 日本一区二区免费在线 | 欧美成人精品第一区二区三区 | 天堂素人在线 | 海绵宝宝第二季全集免费观看 | 国产激情久久久久影院小草 | 亚洲精品国产综合久久一线 | 亚洲精品在线播放 | 四虎网站网址 | 激情自拍网 | 青青国产成人久久激情911 | 摄像头东北对白清晰 | aaa免费看| 亚洲 欧美 国产 在线观看 | 亚洲成年网站在线观看 | 亚洲一区二区三区深夜天堂 | 亚洲欧美日韩成人一区在线 | 国产在线精品香蕉综合网一区 | 日韩人成免费网站大片 | 国产成人精品福利色多多 | 久久热这里面只有精品 | 亚洲网站在线观看 | 欧美精品久久久亚洲 | 亚洲欧美一 | 日韩网站在线 | 成年看片免费高清观看 | 7777奇米四色 |