我最近開始學習jQuery,現在我正在玩弄.ajax()函數。如何訪問jQuery.ajax()在Django視圖中獲取參數
我不知道如何訪問Django中的get參數。
我的代碼如下所示:
jQuery的& HTML:
<div id="browser">
<ul>
{% comment %}
Theres a script for each ctg. Each script fades out #astream, fades in #stream_loading and then it should display #astream with new values based on the GET param in ajax call
Prolly it wont work, but first I need to interact with the GET param in my views.py
{% endcomment %}
{% for ctg in ctgs %}
<script type="text/javascript" charset="utf-8">
(function($) {
$(document).ready(function() {
$("#stream_loading").hide()
$("#browse_{{ctg}}").click(function() {
$("#astream").fadeOut()
$("#stream_loading").fadeIn()
$.ajax({
type: "GET",
url: "/{{defo}}/?param={{ctg}}",
success: function() {
$("#stream_loading").fadeOut()
$("#astream").fadeIn()
}
});
});
});
})(jQuery);
</script>
<li><a id="browse_{{ctg}}" title="{{ctg}}">{{ctg}}</a></li>
{% endfor %}
</ul>
</div>
<div id="astream">
{{ajaxGet}} #just to see whats rendered
{% include "astream.html" %}
</div>
<div id="stream_loading">
loading stream, please wait ...
</div>
Django的:
@https_off
def index(request, template='index.html'):
request.session.set_test_cookie()
path=request.META.get('PATH_INFO')
defo=path[1:path[1:].find('/')+1]
request.session['defo']=defo
defo=request.session['defo']
# build the stream sorted by -pub_date
import itertools
chained=itertools.chain(
model1.objects.order_by('-pub_date').filter(),
model2.objects.order_by('-pub_date').filter(),
)
stream=sorted(chained, key=lambda x: x.pub_date, reverse=True)
ajaxGet=request.GET.get('param','dummy')
if request.is_ajax():
template='astream.html'
ajaxGet=request.GET.get('param',False)
renderParams={'defo':defo, 'stream':stream, 'ajaxGet':ajaxGet}
return render_to_response(template, renderParams, context_instance=RequestContext(request))
然後我試圖說明它在我的模板
{{ ajaxGet }}
乙ut每次渲染爲'虛擬'
在firebug中,我可以看到具有正確的鍵和值的獲取請求。
我在這裏錯過了什麼?
感謝
請張貼您的整個視圖代碼,以便社區可以更好地幫助您。 – Brandon 2012-04-27 14:30:28
應該清楚的是,代碼沒有進入'if request.is_ajax()'塊,否則'ajaxGet'將會是'False'而不是該字符串。所以你需要弄清楚爲什麼。 – 2012-04-27 14:34:22
是的,先生!但是,對於我作爲這個問題的初學者來說,這是非常令人困惑的,爲什麼它沒有進入is_ajax,當從我的pov這是一個Ajax請求。我更新了一些評論的描述 – marlboro 2012-04-27 15:12:35