SlideShare a Scribd company logo
AJAX, Django and Jquery
asika Kuo
For Django Summer
TwD Chapter 15
Django Summer 2
15. AJAX, Django and JQuery
● AJAX
– Asynchronous JavaScript and XML 的縮寫
– 是許多現有技術的組合技
● HTML or XHTML, Cascading Style Sheets,
JavaScript, The Document Object Model, XML,
XSLT, XMLHttpRequest object
– 目的
●
減少使用者等待的時間
●
每次只更新頁面中一部份的資料
Django Summer 3
15. AJAX, Django and JQuery
●
利用 jQuery 來簡化 AJAX 元件的設計
– Bootstrap 已經包含 jQuery 了
●
在 static/js 下面加入 javascript script
– static/js/jquery-2.1.1.js
– static/js/rango-ajax.js
$(document).ready(function() {
// JQuery code to be added in here.
});
Django Summer 4
15. AJAX, Django and JQuery
●
在 templates/rango/base.html 加上
<script src="{% static "/js/jquery-2.1.1.js" %}"></script>
<script src="{% static "/js/rango-ajax.js" %}"></script>
Django Summer 5
15.1. Add a “Like Button”
●
增加讓使用者按讚的功能
Django Summer 6
15.1.1. Workflow
●
修改 category.html template
– 加一個 Like 按鈕
● id=”like”
– 加上一個 template tag 來顯示 like 數
● {{% category.likes %}}
– 建一個叫做 like_count 的 div ,把顯示 like 數的內容丟進
去
● <div id="like_count">{{ category.likes }} </div>
Django Summer 7
15.1.1. Workflow
●
修改 category view 以把 like 數傳給 template
●
建立一個新的 like_category view 用來處理 AJAX request
– 功能:檢驗 request 的正確性,然後增加 like 數
– 接收 GET request
● rango/like_category/?category_id=XXX
– 回覆在該分類下更新過的 like 數,而不是回覆整個 HTML
●
替 rango-ajax.js 增加功能
– 當按下 like 就發送 GET request 到後端,更新頁面上的 like 數並
隱藏按鈕
Django Summer 8
15.1.2. Updating Category Template
●
在 category.html template 新增 like_count div
<p>
<b id="like_count">{{ category.likes }}</b> people like this
category
{% if user.is_authenticated %}
<button id ="likes" data-catid="{{category.id}}"
class="btn btn-mini btn-primary" type="button">Like</button>
{% endif %}
</p>
Django Summer 9
15.1.3. Update the Category View
●
修改 category view
– 傳回 Category 物件以及 ID 和 likes 資訊
# Add category to the context so that we can
access the id and likes
context_dict['category'] = category
Django Summer 10
15.1.4. Create a Like Category View
●
在 views 裡新增 like_category()
@login_required
def like_category(request):
context = RequestContext(request)
cat_id = None
if request.method == 'GET':
cat_id = request.GET['category_id']
likes = 0
if cat_id:
category = Category.objects.get(id=int(cat_id))
if category:
likes = category.likes + 1
category.likes = likes
category.save()
return HttpResponse(likes) <-- 回覆的是 like 數
<-- 透過 GET 取得參數
<-- 要登入才能按讚
Django Summer 11
15.1.4. Create a Like Category View
●
增加新的 URL mapping
url(r'^like_category/$', views.like_category,
name='like_category'),
Django Summer 12
15.1.5. Making the AJAX request
●
修改 rango-ajax.js
– 替 like 按鈕加上送出 GET request 的 event handler
$('#likes').click(function(){
var catid;
catid = $(this).attr("data-catid");
$.get('/rango/like_category/', {category_id: catid},
function(data){
$('#like_count').html(data);
$('#likes').hide();
});
});
<-- DOM element 的 event handler
<-- GET request 成功時的 callback function
<-- 透過
jquery.g
et() 來
發出
GET
request
<-- 取得按鈕的 catid
Django Summer 13
15.2. Adding Inline Category
Suggestions
● 提供一個輸入框,讓使用者一邊輸入分類名稱時,頁面就即
時更新符合輸入名稱的分類列表
– 當使用者在輸入時就會送出一連串的 request 給 server
找出符合的類別
Django Summer 14
15.2.1. Workflow
● 建立 get_category_list(max_results=0, starts_with='') 以回
傳符合要求的分類清單以及數量
● 建立 suggest_category view 處理 GET request
– 找出符合輸入字串的前八名分類
– 把找出的 Category 物件透過 template render 成 HTML
回傳
● 重複利用 category_list.html template
● 建立 URL mapping
Django Summer 15
15.2.1. Workflow
●
在 base.html 的 sidebar 部分加上一個輸入框和用來顯示類
別結果的 div
– 隨著文字的輸入, div 會一直更新內容
●
註冊 event handler 在輸入文字時送出 GET request
Django Summer 16
15.2.2. Parameterise the Get Category
List Function
●
新增 get_category_list helper function
def get_category_list(max_results=0, starts_with=''):
cat_list = []
if starts_with:
cat_list =
Category.objects.filter(name__istartswith=starts_with)
else:
cat_list = Category.objects.all()
if max_results > 0:
if len(cat_list) > max_results:
cat_list = cat_list[:max_results]
for cat in cat_list:
cat.url = encode_url(cat.name)
return cat_list
Django Summer 17
15.2.3. Create a Suggest Category
View
●
新增 suggest_category view
– 預設接受 GET request
– 透過 get_category_list() 找出符合條件的分類,然後從
category_list.html template render 出 HTML
def suggest_category(request):
context = RequestContext(request)
cat_list = []
starts_with = ''
if request.method == 'GET':
starts_with = request.GET['suggestion']
cat_list = get_category_list(8, starts_with)
return render_to_response('rango/category_list.html',
{'cat_list': cat_list }, context)
Django Summer 18
15.2.4. Map View to URL
●
修改 urls.py
url(r'^suggest_category/$', views.suggest_category,
name='suggest_category'),
Django Summer 19
15.2.5. Update Base Template
●
增加查詢的輸入框和顯示結果的 div
<ul class="nav nav-list">
<li class="nav-header">Find a Category</li>
<form>
<label></label>
<li><input class="search-query span10"
type="text" name="suggestion" value=""
id="suggestion" /></li>
</form>
</ul>
{% if cat_list %}
<div id="cats">
{% include 'rango/category_list.html' with
cat_list=cat_list %}
</div>
{% endif %}
Django Summer 20
15.2.6. Add AJAX to Request
Suggestions
●
替輸入框註冊 keyup 的 event handler
$('#suggestion').keyup(function(){
var query;
query = $(this).val();
$.get('/rango/suggest_category/', {suggestion:
query}, function(data){
$('#cats').html(data);
});
});
Django Summer 21
15.2.6. Add AJAX to Request
Suggestions
●
然後一邊輸入就會看到 server 端收到一連串的 request
[14/Jul/2014 07:02:53] "GET /rango/suggest_category/?suggestion=h HTTP/1.1" 200 84
[14/Jul/2014 07:02:53] "GET /rango/suggest_category/?suggestion=he HTTP/1.1" 200 84
[14/Jul/2014 07:02:54] "GET /rango/suggest_category/?suggestion=hel HTTP/1.1" 200 84
[14/Jul/2014 07:02:54] "GET /rango/suggest_category/?suggestion=hell HTTP/1.1" 200 84
[14/Jul/2014 07:02:55] "GET /rango/suggest_category/?suggestion=hello HTTP/1.1" 200 84
[14/Jul/2014 07:02:56] "GET /rango/suggest_category/?suggestion=hello+ HTTP/1.1" 200 84
[14/Jul/2014 07:02:56] "GET /rango/suggest_category/?suggestion=hello+w HTTP/1.1" 200 84
[14/Jul/2014 07:02:56] "GET /rango/suggest_category/?suggestion=hello+wo HTTP/1.1" 200 84
[14/Jul/2014 07:02:57] "GET /rango/suggest_category/?suggestion=hello+wor HTTP/1.1" 200 84
[14/Jul/2014 07:02:57] "GET /rango/suggest_category/?suggestion=hello+worl HTTP/1.1" 200 84
[14/Jul/2014 07:02:57] "GET /rango/suggest_category/?suggestion=hello+world HTTP/1.1" 200 84

More Related Content

What's hot

Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
Morgan Stone
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For MobileGlan Thomas
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
Robert DeLuca
 
ReactでGraphQLを使っている
ReactでGraphQLを使っているReactでGraphQLを使っている
ReactでGraphQLを使っている
Takahiro Kobaru
 
Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8
Théodore Biadala
 
Sprout core and performance
Sprout core and performanceSprout core and performance
Sprout core and performanceYehuda Katz
 
Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018
Joke Puts
 
Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
cfc
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
scottw
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Knoldus Inc.
 
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark BrocatoSenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
Sencha
 
Crafting [Better] API Clients
Crafting [Better] API ClientsCrafting [Better] API Clients
Crafting [Better] API Clients
Wellfire Interactive
 
Web api's
Web api'sWeb api's
Web api's
umesh patil
 
Fewd week6 slides
Fewd week6 slidesFewd week6 slides
Fewd week6 slides
William Myers
 
Why You Shouldn't Write OO
Why You Shouldn't Write OO Why You Shouldn't Write OO
Why You Shouldn't Write OO Yehuda Katz
 
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
Databricks
 
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
Matthew Tovbin
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesKaniska Mandal
 

What's hot (19)

Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
 
ReactでGraphQLを使っている
ReactでGraphQLを使っているReactでGraphQLを使っている
ReactでGraphQLを使っている
 
Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8
 
Sprout core and performance
Sprout core and performanceSprout core and performance
Sprout core and performance
 
Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018
 
Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark BrocatoSenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
 
Crafting [Better] API Clients
Crafting [Better] API ClientsCrafting [Better] API Clients
Crafting [Better] API Clients
 
Web api's
Web api'sWeb api's
Web api's
 
Fewd week6 slides
Fewd week6 slidesFewd week6 slides
Fewd week6 slides
 
Why You Shouldn't Write OO
Why You Shouldn't Write OO Why You Shouldn't Write OO
Why You Shouldn't Write OO
 
Wordpress hooks
Wordpress hooksWordpress hooks
Wordpress hooks
 
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
 
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml Classes
 

Viewers also liked

Bahasa Inggris IX
Bahasa Inggris IXBahasa Inggris IX
Bahasa Inggris IX
ahankshabieb
 
TangoWithDjango - ch8
TangoWithDjango - ch8TangoWithDjango - ch8
TangoWithDjango - ch8Asika Kuo
 
нептун
нептуннептун
нептунDRNanno
 
tangowithdjango - Ch12
tangowithdjango - Ch12tangowithdjango - Ch12
tangowithdjango - Ch12Asika Kuo
 
Inggris1
Inggris1Inggris1
Inggris1
ahankshabieb
 
History of the Caldecott Medal
History of the Caldecott MedalHistory of the Caldecott Medal
History of the Caldecott Medal
cutebluefrog
 

Viewers also liked (7)

Bahasa Inggris IX
Bahasa Inggris IXBahasa Inggris IX
Bahasa Inggris IX
 
TangoWithDjango - ch8
TangoWithDjango - ch8TangoWithDjango - ch8
TangoWithDjango - ch8
 
нептун
нептуннептун
нептун
 
Social media sentinel
Social media sentinelSocial media sentinel
Social media sentinel
 
tangowithdjango - Ch12
tangowithdjango - Ch12tangowithdjango - Ch12
tangowithdjango - Ch12
 
Inggris1
Inggris1Inggris1
Inggris1
 
History of the Caldecott Medal
History of the Caldecott MedalHistory of the Caldecott Medal
History of the Caldecott Medal
 

Similar to tangowithdjango - Ch15

Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
zekeLabs Technologies
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
clammyhysteria698
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
clammyhysteria698
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
clammyhysteria698
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
somberfan2012
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
flagrantlawsuit53
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
ludicrousexcerp10
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
successfuloutdo12
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
somberfan2012
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
somberfan2012
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
ludicrousexcerp10
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
somberfan2012
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
somberfan2012
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
successfuloutdo12
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
successfuloutdo12
 
Ch9 .Best Practices for Class-Based Views
Ch9 .Best Practices  for  Class-Based ViewsCh9 .Best Practices  for  Class-Based Views
Ch9 .Best Practices for Class-Based Views
Willy Liu
 
django-sitecats 0.4.0 : Python Package Index
django-sitecats 0.4.0 : Python Package Indexdjango-sitecats 0.4.0 : Python Package Index
django-sitecats 0.4.0 : Python Package Index
flagrantlawsuit53
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
Django
DjangoDjango
Django
Kangjin Jun
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 

Similar to tangowithdjango - Ch15 (20)

Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
Ch9 .Best Practices for Class-Based Views
Ch9 .Best Practices  for  Class-Based ViewsCh9 .Best Practices  for  Class-Based Views
Ch9 .Best Practices for Class-Based Views
 
django-sitecats 0.4.0 : Python Package Index
django-sitecats 0.4.0 : Python Package Indexdjango-sitecats 0.4.0 : Python Package Index
django-sitecats 0.4.0 : Python Package Index
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django
DjangoDjango
Django
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 

Recently uploaded

Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 

Recently uploaded (20)

Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 

tangowithdjango - Ch15

  • 1. AJAX, Django and Jquery asika Kuo For Django Summer TwD Chapter 15
  • 2. Django Summer 2 15. AJAX, Django and JQuery ● AJAX – Asynchronous JavaScript and XML 的縮寫 – 是許多現有技術的組合技 ● HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, XMLHttpRequest object – 目的 ● 減少使用者等待的時間 ● 每次只更新頁面中一部份的資料
  • 3. Django Summer 3 15. AJAX, Django and JQuery ● 利用 jQuery 來簡化 AJAX 元件的設計 – Bootstrap 已經包含 jQuery 了 ● 在 static/js 下面加入 javascript script – static/js/jquery-2.1.1.js – static/js/rango-ajax.js $(document).ready(function() { // JQuery code to be added in here. });
  • 4. Django Summer 4 15. AJAX, Django and JQuery ● 在 templates/rango/base.html 加上 <script src="{% static "/js/jquery-2.1.1.js" %}"></script> <script src="{% static "/js/rango-ajax.js" %}"></script>
  • 5. Django Summer 5 15.1. Add a “Like Button” ● 增加讓使用者按讚的功能
  • 6. Django Summer 6 15.1.1. Workflow ● 修改 category.html template – 加一個 Like 按鈕 ● id=”like” – 加上一個 template tag 來顯示 like 數 ● {{% category.likes %}} – 建一個叫做 like_count 的 div ,把顯示 like 數的內容丟進 去 ● <div id="like_count">{{ category.likes }} </div>
  • 7. Django Summer 7 15.1.1. Workflow ● 修改 category view 以把 like 數傳給 template ● 建立一個新的 like_category view 用來處理 AJAX request – 功能:檢驗 request 的正確性,然後增加 like 數 – 接收 GET request ● rango/like_category/?category_id=XXX – 回覆在該分類下更新過的 like 數,而不是回覆整個 HTML ● 替 rango-ajax.js 增加功能 – 當按下 like 就發送 GET request 到後端,更新頁面上的 like 數並 隱藏按鈕
  • 8. Django Summer 8 15.1.2. Updating Category Template ● 在 category.html template 新增 like_count div <p> <b id="like_count">{{ category.likes }}</b> people like this category {% if user.is_authenticated %} <button id ="likes" data-catid="{{category.id}}" class="btn btn-mini btn-primary" type="button">Like</button> {% endif %} </p>
  • 9. Django Summer 9 15.1.3. Update the Category View ● 修改 category view – 傳回 Category 物件以及 ID 和 likes 資訊 # Add category to the context so that we can access the id and likes context_dict['category'] = category
  • 10. Django Summer 10 15.1.4. Create a Like Category View ● 在 views 裡新增 like_category() @login_required def like_category(request): context = RequestContext(request) cat_id = None if request.method == 'GET': cat_id = request.GET['category_id'] likes = 0 if cat_id: category = Category.objects.get(id=int(cat_id)) if category: likes = category.likes + 1 category.likes = likes category.save() return HttpResponse(likes) <-- 回覆的是 like 數 <-- 透過 GET 取得參數 <-- 要登入才能按讚
  • 11. Django Summer 11 15.1.4. Create a Like Category View ● 增加新的 URL mapping url(r'^like_category/$', views.like_category, name='like_category'),
  • 12. Django Summer 12 15.1.5. Making the AJAX request ● 修改 rango-ajax.js – 替 like 按鈕加上送出 GET request 的 event handler $('#likes').click(function(){ var catid; catid = $(this).attr("data-catid"); $.get('/rango/like_category/', {category_id: catid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); <-- DOM element 的 event handler <-- GET request 成功時的 callback function <-- 透過 jquery.g et() 來 發出 GET request <-- 取得按鈕的 catid
  • 13. Django Summer 13 15.2. Adding Inline Category Suggestions ● 提供一個輸入框,讓使用者一邊輸入分類名稱時,頁面就即 時更新符合輸入名稱的分類列表 – 當使用者在輸入時就會送出一連串的 request 給 server 找出符合的類別
  • 14. Django Summer 14 15.2.1. Workflow ● 建立 get_category_list(max_results=0, starts_with='') 以回 傳符合要求的分類清單以及數量 ● 建立 suggest_category view 處理 GET request – 找出符合輸入字串的前八名分類 – 把找出的 Category 物件透過 template render 成 HTML 回傳 ● 重複利用 category_list.html template ● 建立 URL mapping
  • 15. Django Summer 15 15.2.1. Workflow ● 在 base.html 的 sidebar 部分加上一個輸入框和用來顯示類 別結果的 div – 隨著文字的輸入, div 會一直更新內容 ● 註冊 event handler 在輸入文字時送出 GET request
  • 16. Django Summer 16 15.2.2. Parameterise the Get Category List Function ● 新增 get_category_list helper function def get_category_list(max_results=0, starts_with=''): cat_list = [] if starts_with: cat_list = Category.objects.filter(name__istartswith=starts_with) else: cat_list = Category.objects.all() if max_results > 0: if len(cat_list) > max_results: cat_list = cat_list[:max_results] for cat in cat_list: cat.url = encode_url(cat.name) return cat_list
  • 17. Django Summer 17 15.2.3. Create a Suggest Category View ● 新增 suggest_category view – 預設接受 GET request – 透過 get_category_list() 找出符合條件的分類,然後從 category_list.html template render 出 HTML def suggest_category(request): context = RequestContext(request) cat_list = [] starts_with = '' if request.method == 'GET': starts_with = request.GET['suggestion'] cat_list = get_category_list(8, starts_with) return render_to_response('rango/category_list.html', {'cat_list': cat_list }, context)
  • 18. Django Summer 18 15.2.4. Map View to URL ● 修改 urls.py url(r'^suggest_category/$', views.suggest_category, name='suggest_category'),
  • 19. Django Summer 19 15.2.5. Update Base Template ● 增加查詢的輸入框和顯示結果的 div <ul class="nav nav-list"> <li class="nav-header">Find a Category</li> <form> <label></label> <li><input class="search-query span10" type="text" name="suggestion" value="" id="suggestion" /></li> </form> </ul> {% if cat_list %} <div id="cats"> {% include 'rango/category_list.html' with cat_list=cat_list %} </div> {% endif %}
  • 20. Django Summer 20 15.2.6. Add AJAX to Request Suggestions ● 替輸入框註冊 keyup 的 event handler $('#suggestion').keyup(function(){ var query; query = $(this).val(); $.get('/rango/suggest_category/', {suggestion: query}, function(data){ $('#cats').html(data); }); });
  • 21. Django Summer 21 15.2.6. Add AJAX to Request Suggestions ● 然後一邊輸入就會看到 server 端收到一連串的 request [14/Jul/2014 07:02:53] "GET /rango/suggest_category/?suggestion=h HTTP/1.1" 200 84 [14/Jul/2014 07:02:53] "GET /rango/suggest_category/?suggestion=he HTTP/1.1" 200 84 [14/Jul/2014 07:02:54] "GET /rango/suggest_category/?suggestion=hel HTTP/1.1" 200 84 [14/Jul/2014 07:02:54] "GET /rango/suggest_category/?suggestion=hell HTTP/1.1" 200 84 [14/Jul/2014 07:02:55] "GET /rango/suggest_category/?suggestion=hello HTTP/1.1" 200 84 [14/Jul/2014 07:02:56] "GET /rango/suggest_category/?suggestion=hello+ HTTP/1.1" 200 84 [14/Jul/2014 07:02:56] "GET /rango/suggest_category/?suggestion=hello+w HTTP/1.1" 200 84 [14/Jul/2014 07:02:56] "GET /rango/suggest_category/?suggestion=hello+wo HTTP/1.1" 200 84 [14/Jul/2014 07:02:57] "GET /rango/suggest_category/?suggestion=hello+wor HTTP/1.1" 200 84 [14/Jul/2014 07:02:57] "GET /rango/suggest_category/?suggestion=hello+worl HTTP/1.1" 200 84 [14/Jul/2014 07:02:57] "GET /rango/suggest_category/?suggestion=hello+world HTTP/1.1" 200 84