Django自动完成 - request.is_ajax()始终返回false

时间:2017-03-01 06:14:07

标签: jquery django jquery-ui-autocomplete

Django的新手。尝试设置一个页面,其中包含支持自动填充的文本框。我提到这个post作为指导。出于某种原因,request.is_ajax()始终返回false

主要应用

urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', home),
    url(r'^search_assist/', include('search_assist.urls')),
]

urls.py用于search_assist应用

urlpatterns = [
    url(r'^$', views.search_assist, name='search_assist'),
]

views.py

def search_assist(request):
    if request.is_ajax():
        q = request.GET.get('term', '')
        states = State.objects.filter(state_name_full__icontains = q )[:20]
        results = []
        for state in states:
            state_json = {}
            state_json['id'] = state.id
            state_json['label'] = state.state_name_full
            state_json['value'] = state.state_name_full
            results.append(state_json)
        data = json.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

HTML

{% extends "gif_alpha_test/header.html" %}
  <div class="ui-widget">
      <label for="sassist">Search Assist: </label>
      <input type="text" id="sassist">
  </div>

header.html具有以下jQuery函数。

<script>
$( document ).ready(function() {
    assist();
});
function assist(){
            $.ajaxSetup({
                headers: {'X-Requested-With': 'XMLHttpRequest'}

            $("#sassist").autocomplete({
                source: "/search_assist/",
                minLength: 2,
            });});
        }
</script>

我在类似的说明中看到了很少的其他帖子,但这些帖子的评论/回复并没有帮助。

有关为什么request.is_ajax()始终返回false的任何想法?感谢帮助。

1 个答案:

答案 0 :(得分:0)

在JS调用之上添加它

$.ajaxSetup({
    headers: {'X-Requested-With': 'XMLHttpRequest'}
});