简体   繁体   中英

Select2 with Rails and JSON

I am trying to use select2 with my rails application but cannot get the result displayed in my views. I see the correct json coming in chrome console but cannot get the result displayed in the dropdown ...

Could you please help me ?

Thanks :

Controllers :

def friends
  if params[:term]
    @users = User.where{ ( (first_name =~ my{"%#{params[:term]}%"}) | (last_name =~ my{"%#{params[:term]}%"}) | ( ((first_name.op('||', ' ')).op('||',last_name)) =~ my{"%#{params[:term]}%"}) | ( ((last_name.op('||', ' ')).op('||',first_name)) =~ my{"%#{params[:term]}%"}) ) & ( adult==false ) }
  end
  respond_to do |format|  
    format.html
    format.json { render :json =>{:results => @users.to_json(only: [:id, :first_name, :last_name]) }}
  end
end

My Javascript :

$("#teen_search").select2({
  placeholder: "Search for a teen",
  minimumInputLength: 2,
  ajax: {
    url: "/friends.json",
    dataType:'json',
    data: function (search, page) {
      return {
        term: search, // search term
        page_limit: 10,
      };
    },

    results: function (data, page) {
      return data;
    }
  },
  dropdownCssClass: "bigdrop"
});

I cannot figure what's wrong, thanks for your help

I just edited the controller render_to json and the results in js to fix an error in the chrome console, I know I am close but still cannot get my user first_name and last_name displayed in the field ...

So I ended up doing that :

User_Controller :

def friends
if params[:term]
    @users = User.where{ ( (first_name =~ my{"%#{params[:term]}%"}) | (last_name =~ my{"%#{params[:term]}%"}) | ( ((first_name.op('||', ' ')).op('||',last_name)) =~ my{"%#{params[:term]}%"}) | ( ((last_name.op('||', ' ')).op('||',first_name)) =~ my{"%#{params[:term]}%"}) ) & ( adult==false ) }.select("id,first_name,last_name,avatar,uid")
    @user = @users.paginate(:page => params[:page], :per_page => params[:page_limit])
end
respond_to do |format|  
    format.html
    format.json { 
      render :json => {
        :users => @user,
        :total => @users.count,
        :links => { :self => @user.current_page , :next => @user.next_page}
    } 
  }
end
end

In the JS Script :

    $(document).ready(function() {
    $("#teens_select2").select2({
        placeholder: "Search for a teen",
        minimumInputLength: 1,
        ajax: {
            url: "/friends.json",
            dataType: 'json',
            quietMillis: 300,
            data: function (search, page) {
                return {
                    term: search,
                    page_limit: 10,
                    page: page,
                };
            },
            results: function (data, page) {
            var more = (page * 10) < data.total;                
              return {results: data.users, more: more};
            }
        },
        formatResult: movieFormatResult,
        formatSelection: movieFormatSelection, 
        dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
    });
});

Also formatResult and formatSelection are configured like that before you load the script :

    function movieFormatResult(user) {
    var markup = "<table class='movie-result'><tr>";
    if ( user.uid !== null) {
         markup += "<td class='movie-image'><img src='" + user.avatar + "'/></td>";
    }
    else if (user.uid == null) {
        var gravatar = user.avatar + 40
         markup += "<td class='movie-image'><img src='" + gravatar + "'/></td>";
     }

    markup += "<td class='movie-info'><div class='movie-title'>" + user.first_name +' '+ user.last_name + "</div>";

    markup += "</td></tr></table>"
    return markup;
}

function movieFormatSelection(user) {
    return (user.first_name + ' ' + user.last_name);
}

And the in the view :

<input type ="hidden" id="teens_select2"></input>

I really hope it can be useful.

只需在dataType属性中通过'json'更改'jsonp'即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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