请求AJAX的Django响应

2024-06-03 00:15:44 发布

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

我在我的项目中使用这个JQuery自动完成插件http://www.devbridge.com/projects/autocomplete/jquery/。我遵循了本教程http://tips4php.net/2010/09/ajax-autocomplete-with-jquery-and-php/。在

自动完成的jQuery代码:

$('#add-keywords').autocomplete({ 
        serviceUrl:'/keywords_suggestions',
        minChars:3,
        maxHeight:220,
        width:280,
        zIndex: 9999,
        onSelect: function(value, data){ $('#add-keywords').val(value); },
});

来自JQuery Autocomplete的ajaxget请求没有问题。这就像,如果我在input text中输入“developer”,那么GET请求url将是

^{pr2}$

我在Django中得到参数查询,如下所示:

def kkeywords_suggestions(request):
        if request.is_ajax():
                q = request.GET.get('query', '')
                try:
                        g = KeywordsModel.objects.filter(keyword__startswith=q).order_by('count')
                except KeywordsModel.DoesNotExist:
                        return HttpResponse("not")
                else:
                        for i in range(1,(len(g)+1)):
                                s = []
                                s.append(g[i-1].keyword)
                        to_json = {
                                query: q,
                                suggestions: s,
                                }
                        return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')

Django公司模型.py公司名称:

class KeywordsModel(models.Model):
        keyword = models.CharField(max_length=40, blank=False)
        count = models.IntegerField(max_length=20)

问题从这里出现request.GET.get('query', '')。它显示了错误

ValueError at /keywords_suggestions/
The view information.views.keywords_suggestions didn't return an HttpResponse object.

更新-1

对不起,Chrome网络标签的错误是这样的

Request URL:http://127.0.0.1:8000/keywords_suggestions/?query=web
Request Method:GET
Status Code:500 INTERNAL SERVER ERROR

当我签入那个URL时,它显示空白页。为什么?在

更新-2

我从视图中删除了request.is_ajax()。现在我得到了这个错误:

Exception Type: NameError
Exception Value:    
global name 'query' is not defined
Exception Location: /home/nirmal/try/information/views.py in keywords_suggestions, line 123

为什么django将query作为一个全局名称?它就是我试图从url中获取的那个。在

有谁能帮我为自动完成功能制作一个完美的HttpResponse?在

谢谢!在


Tags: jsonhttpgetreturnismodelsrequestajax
1条回答
网友
1楼 · 发布于 2024-06-03 00:15:44

应该是的。在

to_json = {'query': q, 'suggestions': s}

基本上,{query:q ...python正在寻找变量查询,以便将字典中的键设置为字符串查询可能指向的对象,但是没有这样的变量,因此它返回了一个错误。。。在

global name 'query' is not defined正如错误所述,python正在查找变量查询,它首先在函数范围内进行本地检查,然后向上移动,直到找到全局范围为止,如果找不到它,则抛出该异常。在

相关问题 更多 >