Django實戰(17):ajax !


繼續上一節未完成的任務,現在讓我們來通過ajax請求后台服務。當然首選要實現后台服務。關於“加入購物車”,我們需要的服務是這樣定義的:

[plain] view plain copy
  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類)增加一個方法:

 

[python] view plain copy
  1. def post(self, request, *args, **kwargs):
  2. print request.POST['product']
  3. product = Product.objects.get(id=request.POST['product'])
  4. cart = request.session['cart']
  5. cart.add_product(product)
  6. request.session['cart'] = cart
  7. 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中,迭代產品的部分改成如下的樣子:

 

[html] view plain copy
  1. {% for item in products %}
  2. <divclass="row"style="padding-top:10">
  3. <divclass="span3 media-grid">
  4. <ahref="#">
  5. <imgclass="thumbnail"src="{{item.image_url}}"alt="">
  6. </a>
  7. </div>
  8. <divclass="span6">
  9. <h3>{{item.title}}</h3>
  10. <br/>
  11. {{item.description}}
  12. <br/>
  13. <br/>
  14. <br/>
  15. <divclass="row">
  16. <divclass="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div>
  17. <divclass="span"><aclass="btn primary"productid="{{item.id}}"href="#">加入購物車</a></div>
  18. </div>
  19. </div>
  20. </div>
  21. <divclass="page-header">
  22. </div>
  23. {% endfor %}

其中主要更改了“加入購物車”的<a>標簽,增加productid屬性,並將href改為“#”。這樣我們就可以很方便的為其添加事件:

 

 

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

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

 

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

 

[javascript] view plain copy
  1. //store.html on ready
  2. $('a.btn[productid]').bind("click",function(){
  3. var product_id=$(this).attr("productid");
  4. //alert(product_id);
  5. $.post("/depotapp/API/cart/items/post",
  6. {product:product_id},
  7. function(data){
  8. alert(data);
  9. }
  10. );
  11. }
  12. );

彈出對話框顯示的data就是前面定義的API接口的返回值,即現有購物車中的條目列表。

 

最后,要根據返回的數據更改界面上的購物車顯示。這里為了方便也對html進行了改造。整個完成的depot/templates/depotapp/store.html如下:

 

 

[html] view plain copy
  1. {% extends "base.html" %}
  2. {% block title %} 產品目錄 {% endblock %}
  3. {% block pagename %} 產品目錄 {% endblock %}
  4. {% block content %}
  5. <divclass="row">
  6. <divclass="span10">
  7. {% for item in products %}
  8. <divclass="row"style="padding-top:10">
  9. <divclass="span3 media-grid">
  10. <ahref="#">
  11. <imgclass="thumbnail"src="{{item.image_url}}"alt="">
  12. </a>
  13. </div>
  14. <divclass="span6">
  15. <h3>{{item.title}}</h3>
  16. <br/>
  17. {{item.description}}
  18. <br/>
  19. <br/>
  20. <br/>
  21. <divclass="row">
  22. <divclass="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div>
  23. <divclass="span"><aclass="btn primary"productid="{{item.id}}"href="#">加入購物車</a></div>
  24. </div>
  25. </div>
  26. </div>
  27. <divclass="page-header">
  28. </div>
  29. {% endfor %}
  30. </div><!--span10-->
  31. <divclass="span4">
  32. <h5>我的購物車</h5><br/>
  33. <tableid="tabCart"class="condensed-table">
  34. <tbodyid="items">
  35. </tbody>
  36. <tfoot>
  37. <tr>
  38. <td></td>
  39. <th>總計:</th>
  40. <tdid="totalprice">¥{{cart.total_price|floatformat:"2"}}</td>
  41. </tr>
  42. </tfoot>
  43. </table>
  44. <aclass="btn danger"href="{% url depotapp.views.clean_cart %}">清空</a>
  45. <aclass="btn success"href="#">結算</a>
  46. </div><!--span4-->
  47. {% endblock %}
  48. {% block js %}
  49. <!--js from store.html-->
  50. <script>
  51. function refreshCart(items){
  52. total = 0;
  53. var tbody = $('tbody#items')[0];
  54. tbody.innerHTML = "";
  55. for(var i=0;i<items.length;i++){
  56. total+=items[i].quantity*items[i].unit_price;
  57. $('table#tabCart').append('<tr><td>'+items[i].quantity+'x</td>'+
  58. '<td>'+items[i].product+'</td><td>¥'+items[i].unit_price+
  59. '</td></tr>');
  60. }
  61. $('#totalprice')[0].innerHTML = '$'+total;
  62. }
  63. </script>
  64. {% endblock %}
  65. {% block on_ready %}
  66. //store.html on ready
  67. $.getJSON('/depotapp/API/cart/items/',refreshCart);
  68. $('a.btn[productid]').bind("click",function(){
  69. var product_id=$(this).attr("productid");
  70. //alert(product_id);
  71. $.post("/depotapp/API/cart/items/post",{product:product_id},refreshCart);
  72. }
  73. );
  74. {% 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的最佳實踐。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM