如何在Django中使用AJAX和JSON?

时间:2018-03-18 04:33:49

标签: python json django

我正在使用Django-Haystack-Solr为我们的大学开发搜索引擎。我想要自动建议和拼写检查功能。所以我使用了auto_query()spelling_suggestion()方法。

这是我的views.py文件。截至目前,只有静态脚本不从实际用户那里获取任何形式的输入。

from django.shortcuts import render
from haystack.query import SearchQuerySet
import json
from django.http import HttpResponse

def testpage(request):
    search_keyword = 'stikar'
    data = SearchQuerySet().auto_query(search_keyword)
    spelling = data.spelling_suggestion()

    sqs = SearchQuerySet().autocomplete(context_auto=spelling)
    suggestions = [result.title for result in sqs]
    link = [result.url for result in sqs]
    context = [result.context for result in sqs]


    the_data = json.dumps({
        'results': suggestions,
        'link': link,
        'context': context
    })

    return HttpResponse(the_data, content_type='application/json')

我的主要url.py文件:

from django.conf.urls import url, include
from django.contrib import admin
from search.views import testpage

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^test/', testpage),             # this is where JSON API is being generated
    url(r'^', include('haystack.urls')),  # this is where actual search page with search form is
]

每当我转到该特定视图时,我都希望调用JSON响应。我希望AJAX请求能够执行。

P.S:API正在呈现完美,没有问题。抱歉英语不好。

请向我询问任何额外信息。

谢谢。 :)

2 个答案:

答案 0 :(得分:1)

尝试使用jQuery autocomplete并调用此api

答案 1 :(得分:0)

我的JSON格式是这样的:

{
    'results': [suggestions],
    'link': [link],
    'context': [context]
}

此JSON来自/testpage/,我想在/testquery/中使用它。这里是testquery.html

的代码

假设您要使用查询参数q执行GET方法。

$.ajax({
    type:"GET",
    url:"/testpage/",
    data:{
        'q': <get param value from DOM>
    },
    success:function(data)
        {
            console.log(data.results);
            console.log(data.link);
            console.log(data.context);
        }
});