使用jquery keyup搜索django

时间:2012-09-03 07:21:55

标签: jquery ajax django

我使用jquery keyup函数进行搜索功能。我曾经在模板中查看搜索过的联系人。我的视图如下:

def contacts_profile(request, search_id=None):
    contact = Invitation.objects.filter(send_visitid = request.user.username, accept_status = True,from_user__username__icontains = search_id)
    results = [ x.from_user.username for x in contact ]
    json = simplejson.dumps(results)
    return HttpResponse(json, mimetype='application/javascript')

我的django模板:

<div id="contact_image">
    {% for contact in contacts %}
        {% if contact.from_user.image  %}
            <img src="/site_media/{{contact.from_user.image}}" id="{{contact.from_user.id}}" onclick="profile(this.id)" alt="" style="border-radius: 10px 10px 10px 10px; width:50px; height:50px;"/>{{contact}}<br><br>
        {% else %}
            <img src="/site_media/img/contact-img.png" alt="" />{{contact}}<br><br>
        {% endif %}
    {% endfor %}
    </div>

<div><input type="text" class="form-text" name="search_field" id="id_search_field" placeholder="Search Contacts here" />

请帮助我在ajax中查看此模板中搜索到的联系人:

$("#id_search_field").keyup(function () {
        var a =($('#id_search_field').val());
        alert(a);
        var html_str = ""
        $.ajax({
            "type"      : "GET",
            "url"       : "/profile_information/contacts_profile/" +a+ "/",
            "dataType"  : "json",
            "cache"     : false,
            "success"   : function(json) {
                alert(json)
                    }
                });     
         }); 

帮我查看模板中的json值。

2 个答案:

答案 0 :(得分:0)

我会使用Dajaxice / Dajax。请参阅docs(和my answer here)了解其工作原理。基本上你得到了一个包装器(1)使AJAX调用更加无缝,(2)能够轻松编写HTML修改指令,例如: “将此HTML放入该div”或其他任何内容,放入您的AJAX响应中。

答案 1 :(得分:0)

好吧,我认为你的jquery ajax有点错误:而不是:

$.ajax({
   "type"      : "GET",
   "url"       : "/profile_information/contacts_profile/" +a+ "/",
   "dataType"  : "json",
   "cache"     : false,
   "success"   : function(json) {
        alert(json)
    }
});     

使用:

$.ajax({
   type      : "GET",
   url       : "/profile_information/contacts_profile/" +a+ "/",
   dataType  : "json",
   cache     : false,
   success   : function(json) {
        //see below for the json object
    }
});   

然后将响应对象实际转换为json,执行

json = eval(json);

这样你可以拥有json。&lt; property&gt;呼叫

相关问题