如何在Django视图中访问jQuery.ajax()获取参数

我最近开始学习jQuery,现在我正在使用.ajax()函数。

我无法弄清楚如何在Django中访问get参数。

我的代码看起来像:

Jquery&html:

    {% 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 %} (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);
  • {{ctg}}
  • {% endfor %}
{{ajaxGet}} #just to see whats rendered {% include "astream.html" %}
loading stream, please wait ...

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 }} 

但每次都被渲染成’虚拟’

在firebug中,我可以看到具有正确键和值的get请求。

我在这里想念什么?

谢谢

人们经常在做这种Ajax时经常陷入困境,这并不妨碍链接/按钮的默认操作。 因此,您的Ajax函数永远不会触发,并且您在Django代码中看到的请求是由正常的页面加载引起的 – 这就是为什么is_ajax()为false。

click处理程序提供参数, event和调用event.preventDefault(); 在function的最后。