简体   繁体   English

在Ruby Rails中渲染JSON以实现jQuery自动完成

[英]Render json in ruby rails for jquery autocomplete

This is my code which render json in format {"11":"xyz","14":"abc"} 这是我的代码,以{"11":"xyz","14":"abc"}格式呈现json

def index
    if params[:term] != nil
      @products = Hash[current_user.search(params[:term]).map{|product| [product.id,product.name]}]
      render json: @products.to_json
    end
  end

This is the javascript where I am updating div #results with autocomplete result. 这是我用自动完成结果更新div #results的javascript。 What I want is to make xyz and abc link with the ids associated with it but I am not able to figure out why I am losing ids all I am getting in results as xyz and abc`. 我想要的是使xyzabc与关联的ID链接,但我无法弄清楚为什么我丢失所有以ID为xyz和abc`结果的ID。

$(document).ready(function(){

    $("#search").autocomplete({
        //source: $('#search').data('autocomplete-source'),
        source: "entities#index",

        open: function(e, ui) {
            var list = '';
            var results = $('ul.ui-autocomplete.ui-widget-content a');
            var ent_id = results.html()
            results.each(function() {
                list += '<a href= '+$(this).html()+'/'+ent_id+ '>' +$(this).html()+'</a>'+ '<br />';
            });
            $('#results').html(list);
        }
    })
} )

Right now above javascript code is not working as required because i am not able to get ids. 目前,上面的javascript代码无法按要求运行,因为我无法获取ID。

Thanks 谢谢

I found a soulution for it. 我找到了解决方案。

$(document).ready(function(){

    $( "#search" ).autocomplete(
        {
            source:"entities#index",
            select: function( event, ui ) {
                $( "#search" ).val( ui.item[1] );
                $( "#results").empty();
                $( "#results" ).append( '<a href= '+"entities"+'/'+ui.item[0]+ '>' +ui.item[1]+'</a>' );
                return false;
            }

        }).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>" + item[1] + "</a>" )
            .appendTo( ul );
    };

} )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM