Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

Parse json to jquery ajax autocomplete list from Rails

I never did this before, I am trying to club multiple ldap attributes to be shown for each autocomplete list item.

For example, I search "admin" as sAMAccountName in ldap, and my search function returns two values for each match. sAMAccountName and idnumber, so my list item has to include both sAMAccountName and idnumber. Rather than just sAMAccountName "admin" that was typed in the text field. How can I make jQuery read multiple attributes for each list item?

def search
  if (params[:term] =~ /[a-zA-Z]/)
    @result = User.FindLdap("sAMAccountName", params[:term])
  else
    @result = User.FindLdap("idnumber", params[:term])
  end

  respond_to do |format|
    format.json { render :json=> @result.to_json }
    format.js
  end
end
$(function() {
  $("#term").autocomplete({
    source: function (request, response) {
      $.post("/users/search", request, response);
    },
    minLength: 2,
    select: function () {}
  });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's hard to tell what are attributes in User model but I presume they are sAMAccountName and idnumber, so here is replacement for your source method in jQuery autocomplete

source: function( request, response ) {
    $.ajax({
        url: "/users/search",
        dataType: "json",
        data: {
            term: request.term
        },
        success: function( data ) {
            // remove users in line below if JSON is not prepanded with users attribute 
            response( $.map( data.users, function( user ) {
                return {
                    // this is formated string which will be visible in autocomplete list
                    // example "123213, admin"
                    label: user.idnumber + ", " + user.sAMAccountName, 
                    value: user.idnumber
                }
            }));
        }
    });
},

The code above will convert (map) response from server to format

[ { label: "<idnumber>, <sAMAccountName>" , value: "<idnumber>" }, .....]

Don't worry jQuery autocomplete knows how to handle this array ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...