JQuery自动完成 - 选择后发布数据

时间:2016-12-06 14:01:51

标签: jquery django autocomplete get

我使用Djago + jQuery自动完成功能。汽车完成确实有效。但我不确定如何在用户选择后发送数据。当我发送它时,会显示自动完成检索的所有信息。

的jQuery

$("#tags5").autocomplete({
    minLength:3,
    source: function(req, add){
      var search=$("#tags5").val();
      $.ajax({
        url:'/ajax/',
        async:false,
        dataType:'json',
        type:'GET',
        data:{ 'start': search,},
        success: function(data){
          var suggestions=[];
          $.each(data, function(index, objeto){
            suggestions.push(objeto); 
          });
          add(suggestions);
          #send data
          $.get( "/showlist", { suggestions });
        },
        error:function(err){
          alert("error");
        }
      });
    }
  });   
});

HTML

    <form id='tv' method="GET" action="/showlist">{% csrf_token %}
      <label for="tags5"> </label>
      <input id="tags5" style="width: 500px">
      <button class='btn btn-conf btn-green' type="submit" id="post-btn"  style="width: 200px" >Adicionar</button>
      </form>

的Django

# views.py
def lista(request):
    if request.is_ajax:
        search=request.GET.get('start','')
        tvshow=TvShowModel.objects.filter(tvs_name__icontains=search)
        results=[]
        for tv in tvshow:
            tv_json={}
            tv_json['label']=tv.tvs_name
            tv_json['value']=tv.tvs_name
            results.append(tv_json)

        data_json=json.dumps(results[:5])

    else:
        data_json='fail'

    mimetype="application/json"
    return HttpResponse(data_json,mimetype)

def index(request):
    return render(request, 'webapp/base.html')

# urls.py
    urlpatterns = [
            url(r'^$', views.index, name='index'),
            url(r'^showlist', views.showlist, name='showlist'),
            url(r'^ajax/$',views.lista),
        ]

输出:

  

[06 / Dec / 2016 13:53:40]&#34; GET / showlist?建议%5B0%5D%5Bvalue%5D =跳舞+ + +星级和建议%5B0%5D%5Blabel%5D =跳舞+与+的+星&安培;建议%5B1%5D%5Bvalue%5D = 舞蹈+妈妈&安培;建议%5B1%5D%5Blabel%5D =舞蹈+妈妈&安培;建议%5B2%5D%在+的+边及放5Bvalue%5D =舞蹈+;建议%5B2%5D%的+在+边及放5Blabel%5D =舞蹈+;建议%5B3%5D%5Bvalue%5D =于是+你+想想+你+ CAN +舞蹈和放大器;建议%5B3%5D%5Blabel%5D =于是+你+想想+你+ CAN +舞蹈和放大器;建议%5B4%5D%5Bvalue%5D =舞蹈+学院和放大器;建议%5B4%5D%5Blabel%5D =舞+学院HTTP / 1.1&#34; 200 80211   [06 / Dec / 2016 13:53:45]&#34; GET / showlist?csrfmiddlewaretoken = VaD6qQEWFViTSV1wvI3cNWGARSqZRnxYXeB3bwWsfxyzTBQv1SJ4oN4Yqeny2fMf HTTP / 1.1&#34; 200 80211

我应该只选择舞蹈妈妈的选项,而不是带来所有这些。

我尝试使用更改和选择器事件,但它也没有工作。

3 个答案:

答案 0 :(得分:1)

您可以将视图重写为:

def lista(request):

    mimetype="application/json"

    if request.is_ajax:
        search=request.GET.get('start','')
        tvshow=TvShowModel.objects.filter(tvs_name__icontains=search)
        results=[]
        for tv in tvshow:
            tv_json={}
            tv_json['label']=tv.tvs_name
            tv_json['value']=tv.tvs_name
            results.append(tv_json)

        data_json=json.dumps(results[:5])
        return HttpResponse(data_json,mimetype)

    else:
        data_json='fail'
        return HttpResponse(data_json,mimetype)

自动完成的jQuery示例:

$("#tags5").autocomplete({
            source: function (request, response) {
                    $.ajax({
                        url: "/ajax/",
                        dataType: "json",
                        data: {term: request.term},
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {

                            var results = $.map(data.search_org, function (item) {
                                if (item.sugession.toUpperCase().indexOf(request.term.toUpperCase()) === 0)

                            return {
                                sugession:item.sugession,

                            };

                        });
                        response(results)

                    }

                });

            },
            minLength: 3,
            scroll: true,
            select: function (event, ui) {

                var sugession = ui.item.sugession;
                $('#tags5').val(ui.item.sugession);

                return false;
            }


        }).data("ui-Autocomplete")._renderItem = function (ul, item) {

            return $("<li>").data("item.autocomplete", item).append("<a class='index_list_autocomplete'>" + item.sugession + "</a>").appendTo(ul);

        };

答案 1 :(得分:0)

您需要在自动填充

中添加类似的内容
$("#tags5").autocomplete({
    minLength:3,
    source: function(req, add){ ... },
    select: function( event, ui ) {
              log( "Selected: " + ui.item.value + " aka " + ui.item.id );
              $.ajax({ //send selected item here });
    },
});

答案 2 :(得分:0)

在阅读了上述一些内容后找到了解决方案:

我在输入中添加了attr名称:

 <form id='tv' method="GET" action="/showlist">{% csrf_token %}
      <label for="tags5"> </label>
      <input id="tags5" style="width: 500px" **name="tvshowname"** class="subscribe-input">
      <button class='btn btn-conf btn-green' type="submit" id="post-btn"  style="width: 220px" >Adicionar</button>
      </form>

从jquery中删除了以下行:

 $.get( "/showlist", { suggestions });

输出:

  

[06 / Dec / 2016 20:37:04]“GET / showlist?csrfmiddlewaretoken = JIWLTlNvxV2NfZj7LW2TirOFawI2bckvLMUIE1517xitgF86h6ILTic3JSFBm4zM&amp; tvshowname = Prison + Break HTTP / 1.1”200 66129

没有帖子只发送我选择的结果。

感谢您的帮助!