我一直在嘗試將我的代碼從基於Django的視圖切換到基於類的視圖,但我無法理解如何處理Django CBV中的AJAX。使用Django基於類的視圖處理AJAX時遇到問題
例如,假設我在我的Django博客項目中有這個實時搜索功能。 (對不起,我試圖使它儘可能簡單。)
urls.py
url(r'^search/$', search_page),
forms.py
class SearchForm(forms.Form):
query = forms.CharField()
entire_search_page.html
<form id="search-form" method="get" action=".">
{{form.as_p}}
<input type="submit" value="search" />
</form>
<div id="search-results">
{% include "just_the_result.html" %}
</div>
個
just_the_result.html
{% for post in post_list %}
<li>{{ post.title }}</li>
views.py
def search_page(request):
form = SearchForm()
post_list = []
if 'query' in request.GET:
form = SearchForm({'query': query})
post_list = Post.objects.filter(title__icontains=query)
if request.GET.has_key('ajax'):
variables = RequestContext(request, {
'post_list': post_list,
})
return render_to_response('just_the_result.html', variables)
else:
variables = RequestContext(request, {
'form': form,
'post_list': post_list,
})
return render_to_response('entire_search_page.html', variables)
search.js
$(document).ready(function() {
$("#search-form").submit(search_submit);
});
function search_submit() {
var query = $("#id_query").val();
$("#search-results").load(
"/search/?ajax&query=" + encodeURIComponent(query)
);
return false;
}
所以基本上,我展示了整個搜索頁面當請求時是正常的,如果請求是AJAX,則只顯示「just_the_result.html」。這在我運行服務器時正常工作,但我想將此視圖更改爲基於類的視圖。
這是我到目前爲止有:
views.py
class PostSearch(ListView):
model = Post
template_name = 'app_blog/search.html'
context_object_name = 'post_list'
def get_queryset(self):
queryset = super(PostSearch, self).get_queryset()
query = self.request.GET.get('query')
if query:
return queryset.filter(title__icontains=query)
else:
return queryset
我想,當請求是正常的這種正常工作。但是,當請求是AJAX請求時,我不知道該怎麼做!在基於函數的視圖中,我可以根據請求是否是AJAX返回不同的模板和變量,但我認爲這在CBV中不是必需的,甚至不可能。還有一個問題。最近我一直在閱讀有關RESTful的設計。上面的代碼是否被認爲是「RESTful」?我很難理解如何精確使用REST API。