2

私は最近jQueryを学び始め、今は.ajax()関数で遊んでいます。

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

しかし、毎回「ダミー」としてレンダリングされます

ファイアバグでは、適切なキーと値を持つgetリクエストを確認できます。

ここで何が恋しいですか?

ありがとう

4

1 に答える 1

2

この種のAjaxを実行するときに人々がしばしば陥る落とし穴が頻繁にあり、それはリンク/ボタンのデフォルトのアクションを妨げていません。したがって、Ajax関数が起動する機会はなく、Djangoコードに表示されているリクエストは、通常のページの読み込みが原因で発生します。これis_ajax()がfalseである理由です。

ハンドラーclickにパラメーター、、を指定し、関数の最後でevent呼び出します。event.preventDefault();

于 2012-04-27T15:38:26.887 に答える