Memor.の 2014-04-29 18:12 采纳率: 100%
浏览 75

Django的AJAX

I'm trying to incorporate a simple AJAX function with Django and I've no idea what I'm doing wrong. request.is_ajax() is returning False and even when I do event.preventDefault(), the form is still being submitted.

Here is the view:

def search(request):
    if request.is_ajax():
        search_text = request.POST.get('search_text', False)
    else:
        search_text = 'Not AJAX'
    return HttpResponse(search_text)

The JS:

$(function(){

    $('#search_form').submit(function(event){
        event.preventDefault();

        $.ajax({
            type: 'post',
            url: {% url 'users:search' %},
            dataType: 'html',
            data: {
                'search_text': $('#search').val(),
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            success: function(data){
                $('#search-results').html(data);
                },
            failure: function(data){
                alert('Got an error');
                }
        });
        return false;
    });

});

And the HTML:

 <div class="col-md-4">
            <h5>Search</h5>
            <form action="{% url 'users:search' %}" method="POST" id="search_form" name="search_form">
                {% csrf_token %}
                <input type="text" id="search" name="search">
                <input type="submit" value="Search">
            </form>
            <ul id="search-results">
                {% if users %}
                    {% for user in users %}
                        <li><a href="{% url 'users:detail' user.id %}">{{ user.username }}</a></li>
                    {% endfor %}
                    {% else %}
                        <p>No user available</p>
                {% endif %}
            </ul>
        </div>
  • 写回答

3条回答 默认 最新

  • weixin_33709364 2014-04-29 18:23
    关注

    I believe the form is actually always submitted because you have an error in your js. In the $ajax options, the url should be surrounded with quotes:

    $.ajax({
        type: 'post',
        url: '{% url 'users:search' %}',
        ...
    });
    

    In your question you say that request.is_ajax is False, which implies the ajax call is actually performed. I don't think that's the case here. Given the above code sample the call does not happen at all and none of the view code should be executed.

    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码