如何在Django中使用AJAX和JSON?

2024-04-20 10:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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请求。你知道吗

附言:API被渲染得非常好,没有问题。对不起,英语不好。你知道吗

请问我任何额外的信息。你知道吗

谢谢你。:)


Tags: djangofromimportjsonurlautosearchdata
2条回答

尝试使用jQuery autocomplete并调用此api

我有如下JSON格式:

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

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

假设您希望使用query paramq执行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);
        }
});

相关问题 更多 >