简体   繁体   中英

Django Ajax Values Returned but Not Being Displayed in Drop-down List

I have a simple search box where I use Ajax to display blog titles in drop down suggestion list.

I get no errors and I do see the data populated when I use inspect element > network > response through the browser. The browser is correctly fetching /articles/search/ on every key stroke and the data are there, just not being displayed in my template.

Any suggestions?

urls.py

url(r'^search/$', 'article.views.search_titles'),

Views.py

def search_titles(request):
if request.method == "POST":
    search_text = request.POST['search_text']
else:
    search_text = ''

articles= Articles.objects.filter(title__icontains=search_text)

return render_to_response('ajax_search.html', {'articles' : articles})

ajax_search.html

{% for article in articles %}
    <li><a href="/{{ article.slugname }}/">{{ article.title }}</a></li>
{% endfor %}

articles.html

{% extends "base.html" %}
{% block sidebar %}
<h3>Search</h3>
{% csrf_token %}
<input type="text" id="search" name="search">
<ul id="search-results">

</ul>
{% endblock %}

base.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="{% static "js/jquery-1.11.0.min.js" %}"></script>
<script src="{% static "js/ajax.js" %}"></script>
....

ajax.js

$(function(){

$('#search').keyup(function() {

    $.ajax({
        type: "POST",
        url: "/articles/search/",
        data: {
            'search_text' : $('#search').val(),
            'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
        },
        success: searchSuccess,
        dataType: 'html'
    });

});

});

function searchSuccess(data, textStatus, jqXHR)
{
$('#serch-results').html(data);
}

I dont know how necessary this is since it was a typographical error rather than a logical one and probably wont apply to many people, so for the next person who comes along, this probably isn't the solution you're looking for, but it might be a good lesson. Whenever you've looked everywhere for a bug and you're sure you've done everything right, take a break. Come back later with fresh eyes. The problem is never where you think it is.

In this case, he was missing the A in his searchSuccess() definition where $('#serch-results') should have been $('search-results) .

edit: also, on django's development server i've run into problems with ajax and one or two other functions where changes in code stop taking effect. Sometimes you have to restart the server, the terminal, or the entire machine(I suggest in that order)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM