Django和AJAX——我做错了什么?

时间:2022-09-06 21:36:51

I'm trying to write a simple search server, using Django with AJAX. The server itself works fine, but I am still struggling with adding autocomplete to the search widget.

我正在尝试使用Django和AJAX编写一个简单的搜索服务器。服务器本身工作得很好,但是我仍然在为向search小部件添加autocomplete而烦恼。

(I don't want to use available Django snippets, since they don't do exactly what I want, are hard to customize, and don't teach me the basics the way writing the interface from scratch does)

(我不想使用可用的Django片段,因为它们不能完全按照我的要求进行,很难自定义,也不教我从头编写接口的基本方法)

On the client (Javascript) side, I'm using YUI because it looks simpler - but don't mind switching to jQuery, so please don't fixate on that.

在客户端(Javascript)方面,我使用YUI,因为它看起来更简单——但是不介意切换到jQuery,所以请不要关注它。

In YUI, an autocomplete box takes three parameters: input,container and dataSource. The first two are just the widgets, and the third one is interesting.

在YUI中,自动完成框接受三个参数:输入、容器和数据源。前两个只是小部件,第三个很有趣。

If I write:

如果我写:

var oDS = new YAHOO.util.LocalDataSource(["apples","apples2", "broccoli", "cherries"]);
var oAC = new YAHOO.widget.AutoComplete("myInput", "myContainer", oDS);

in my <script>, I get an autocomplete box which autocompletes these terms.

在我的

When I try to replaces the LocalDataSource with a remote datasource, for example by choosing var oDS = new YAHOO.util.ScriptNodeDataSource("127.0.0.1:8000/getNames/"), and setting up an apropriate view, no autocomplete happens.

当我尝试用一个远程数据源替换LocalDataSource时,例如,通过选择var oDS = new YAHOO.util.ScriptNodeDataSource(“127.0.1:8000 /getNames/”),并设置一个aowner视图,不会自动完成。

What I know about the problem:

我对这个问题的了解:

  1. I know that the view gets called (by debug printing) - so that isn't the problem.
  2. 我知道视图被调用(通过调试打印)——所以这不是问题。
  3. I return a json array by jresponse = simplejson.dumps(response_array); return HttpResponse(jresponse, mimetype='application/javascript'); I don't think there's any problem with that, since I can access that view directly and get a textual representation of the json when I do.
  4. 通过jresponse = simplejson.dumps(response_array)返回json数组;返回HttpResponse(jresponse mimetype = '应用程序/ javascript ');我不认为这有什么问题,因为我可以直接访问该视图,并在我做的时候得到json的文本表示。
  5. Maybe there's a problem with the input-type that the local data source expects - I'm not sure how to set it.
  6. 也许本地数据源所期望的输入类型有问题——我不确定如何设置它。

Any help (including how to do this correctly in jQuery - I don't mind dumping YUI) would be much appreciated.

任何帮助(包括如何在jQuery中正确执行此操作——我不介意丢弃YUI)都将非常感谢。


Edit: After the first two comments (thanks!), I installed firebug, and started playing with it. It's really messy, however, since the Yahoo toolbar has lots of code, and I don't know where to break it. Is there some easy way to have firebug only show me json/xml elements?

编辑:在前两个评论(谢谢!)之后,我安装了firebug,并开始使用它。但是,这真的很麻烦,因为Yahoo工具条有很多代码,我不知道该从哪里破解它。有什么简单的方法可以让firebug只显示json/xml元素吗?

@Marat: I did that already (accessing my view), and it returns a string representation of the JSON (at least that's what my browser shows). Is that what I should expect?

@Marat:我已经这样做了(访问我的视图),它返回JSON的字符串表示形式(至少我的浏览器是这样显示的)。这是我应该期待的吗?

@pastylegs: Here's the code:

@pastylegs:这里的代码:

 <div id="myAutoComplete">
    <input id="myInput" type="text">
    <div id="myContainer"></div>
    </br></br>
    <input type="submit">
</div>

 <script type="text/javascript">
YAHOO.example.BasicLocal = function() {
{%block oDS%}
// Use a LocalDataSource
var oDS = new YAHOO.util.LocalDataSource(["apples","apples2", "broccoli", cherries"]);
//for remote - oDS = new YAHOO.util.ScriptNodeDataSource("127.0.0.1:8000/getNames/")


// Instantiate the AutoComplete
var oAC = new YAHOO.widget.AutoComplete("myInput", "myContainer", oDS);
oAC.prehighlightClassName = "yui-ac-prehighlight";
oAC.useShadow = true;

return {
    oDS: oDS,
    oAC: oAC
};
}();
</script>

The Django view:

Django的观点:

def getNamesXML(request):
    response_array=['Apples','Oranges']
    print response_array
    jresponse = simplejson.dumps(response_array)
    print jresponse
    return HttpResponse(jresponse, mimetype='application/javascript')

Thanks a lot!

谢谢!

1 个解决方案

#1


1  

I don't know anything about YUI, but I can give you a working jQuery example. Main difference I see with your code is the mimetype: as discussed in this question, you should use application/json. That said, I don't think it'll make a big difference.

我对YUI一无所知,但是我可以给你一个jQuery示例。我在您的代码中看到的主要区别是mimetype:正如在这个问题中讨论的,您应该使用application/json。也就是说,我不认为这有什么大的区别。

For the view, use something along these lines:

对于视图,使用以下内容:

def autosuggest(request):
    query = request.GET.get('term') # jQuery autosuggest input so far
    f = MyModel.objects.filter(name__icontains=query)
    response = [p[0] for p in f.order_by("name")[:10].values_list("name")]
    return HttpResponse(simplejson.dumps(response), mimetype="application/json")

This assumes f is a QuerySet on a model that has a name field, and you want the first 10 matches. In your template, the following should do:

这假设f是一个具有name字段的模型上的QuerySet,您需要前10个匹配。在您的模板中,如下所示:

$('#myInput').autocomplete({
    source: '{% url myapp.views.autosuggest %}',
    minLength: 2, // Two characters are needed before suggestions show
    select: function(event, ui) { // Callback function for selection
        $('#myInput').val(ui.item.value);
    },
});

#1


1  

I don't know anything about YUI, but I can give you a working jQuery example. Main difference I see with your code is the mimetype: as discussed in this question, you should use application/json. That said, I don't think it'll make a big difference.

我对YUI一无所知,但是我可以给你一个jQuery示例。我在您的代码中看到的主要区别是mimetype:正如在这个问题中讨论的,您应该使用application/json。也就是说,我不认为这有什么大的区别。

For the view, use something along these lines:

对于视图,使用以下内容:

def autosuggest(request):
    query = request.GET.get('term') # jQuery autosuggest input so far
    f = MyModel.objects.filter(name__icontains=query)
    response = [p[0] for p in f.order_by("name")[:10].values_list("name")]
    return HttpResponse(simplejson.dumps(response), mimetype="application/json")

This assumes f is a QuerySet on a model that has a name field, and you want the first 10 matches. In your template, the following should do:

这假设f是一个具有name字段的模型上的QuerySet,您需要前10个匹配。在您的模板中,如下所示:

$('#myInput').autocomplete({
    source: '{% url myapp.views.autosuggest %}',
    minLength: 2, // Two characters are needed before suggestions show
    select: function(event, ui) { // Callback function for selection
        $('#myInput').val(ui.item.value);
    },
});