Django使用Jquery和AJAX时的简单问题

时间:2012-03-15 12:30:16

标签: jquery ajax django

我正在尝试仅渲染用于响应AJX调用的表,但它呈现整个模板。 如何在使用render_to_response时只渲染表?

模板:

<html>
    <head>
        <title> Hash Searcher </title>
        <script type="text/javascript" src="{{STATIC_URL}}jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#searchSubmit').click(function() {
                    q = $('#q').val();
                    $('#results').html('&nbsp;').load('/?mdhash=' + q );

                });
            });
            $(document).ajaxStart(function() {
                $('#spinner').show();
            }).ajaxStop(function() {
                $('#spinner').hide();
            });
        </script>
    </head>
    <body style="text-align: center; ">
        <input id="q" type="text" name="mdhash" value="{{ mdhash }}" style="text-align: center; "size=60 />
        <br>
        <input id="searchSubmit" type="submit" value="Search" />
        <br>
        <div style="display:none" id="spinner"><img src="{{STATIC_URL}}spinner.gif"/></div>
        <br>
        <span id="results">
        {% if plain %}
        <table>
            <tbody>
                <tr>
                    <td><small>#</small></td>
                    <td><small>Hash</small><br></td>
                    <td><small>Clear</small><br></td>
                    <td><small>Type</small><br></td>
                    <td><small>DB</small><br></td>
                </tr>
                {% for hash, clear in plain.items %}
                <tr>
                    <td><small>{{ forloop.counter }}</small></td>
                    <td><small>{{ hash }}</small><br></td>
                    <td><small><strong>{{ clear.0 }}</strong></small><br></td>
                    <td><small>{{ clear.1 }}</small><br></td>
                    <td><small>{{ clear.2 }}</small><br></td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% endif %}
        </span>
    </body>
</html>

查看:

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template.context import RequestContext
import core.models, time

def search(request):
    req = request.GET.get('mdhash', '')
    plain = {}
    try:
        plain[req] = (core.models.Hash_md5.objects.get(hash=req).plain, 'md5', 'iCrack')
    except:
        pass
    #aif request.is_ajax():
    #    time.sleep(5)
    #    return HttpResponse({plain: 'plain'})
    #else:
    return render_to_response('index.html', locals(), context_instance = RequestContext(request))

1 个答案:

答案 0 :(得分:1)

如果您将模板的<table>部分考虑在内(并使用{% include ... %}将其包含在页面模板中),那么您只需渲染该子模板if request.is_ajax()即可我将能够通过jQuery替换页面的那一部分。