最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I return arbitrary JSON objects to a jQuery Autocomplete list? - Stack Overflow

programmeradmin4浏览0评论

jQuery part:

I have a jQuery UI 1.8 Autoplete form that fetches remote JSON data from a Rails controller.

$('input#test').autoplete({
    source: function( request, response ) {
      $.getJSON(
        "<%= find_stuff_url(:format => :json) %>",
        request,
        function(data){
          console.log(data);
          function(data) {
            $.map(data, function(item) {
            return {
              "label" : item.control_point.label,
              "value" : item.control_point.geonames_uri
            }
            });
        });
    },
    minLength: 2,
    select: function( event, ui ) {
        // ...
    }
  });

… what I get returned:

This Rails controller just returns an array of Objects (actually, ActiveRecord instances), serialized into JSON. I would like to use this data to populate the Autoplete list. Right now, what I receive is an array of serialized ActiveRecord objects – for example one of these objects could be:

Object
  control_point: Object
    geonames_uri: "/"
    label: "New York (US)"
    lat: "40.7142691"
    lng: "-74.0059729"
    map_id: 1
    name: "New York City"

What I need:

However, jQuery Autoplete probably wants a JSON array of objects that carry id and label to populate its list — yet I don't have these. This is what the documentation says:

A response callback, which expects a single argument to contain the data to suggest to the user. This data […] can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties).

I don't quite understand what's meant by "String-Array or Object-Array with label/value/both" properties.

In this example, my output would be a list of those control_point Objects, shown like:

label: "New York (US)", value: <the geonames_uri>
label: "New York (Somewhere else)", value: <another geonames_uri>
…

I tried to adapt the code from the documentation using $.map, but it doesn't seem to work (i.e. the autoplete shows nothing).

How do I pass an arbitrary JSON object to jQuery Autoplete, so it shows a list of results? More explicitly: What do I have to put in function(data){}?

jQuery part:

I have a jQuery UI 1.8 Autoplete form that fetches remote JSON data from a Rails controller.

$('input#test').autoplete({
    source: function( request, response ) {
      $.getJSON(
        "<%= find_stuff_url(:format => :json) %>",
        request,
        function(data){
          console.log(data);
          function(data) {
            $.map(data, function(item) {
            return {
              "label" : item.control_point.label,
              "value" : item.control_point.geonames_uri
            }
            });
        });
    },
    minLength: 2,
    select: function( event, ui ) {
        // ...
    }
  });

… what I get returned:

This Rails controller just returns an array of Objects (actually, ActiveRecord instances), serialized into JSON. I would like to use this data to populate the Autoplete list. Right now, what I receive is an array of serialized ActiveRecord objects – for example one of these objects could be:

Object
  control_point: Object
    geonames_uri: "http://sws.geonames/5128581/"
    label: "New York (US)"
    lat: "40.7142691"
    lng: "-74.0059729"
    map_id: 1
    name: "New York City"

What I need:

However, jQuery Autoplete probably wants a JSON array of objects that carry id and label to populate its list — yet I don't have these. This is what the documentation says:

A response callback, which expects a single argument to contain the data to suggest to the user. This data […] can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties).

I don't quite understand what's meant by "String-Array or Object-Array with label/value/both" properties.

In this example, my output would be a list of those control_point Objects, shown like:

label: "New York (US)", value: <the geonames_uri>
label: "New York (Somewhere else)", value: <another geonames_uri>
…

I tried to adapt the code from the documentation using $.map, but it doesn't seem to work (i.e. the autoplete shows nothing).

How do I pass an arbitrary JSON object to jQuery Autoplete, so it shows a list of results? More explicitly: What do I have to put in function(data){}?

Share Improve this question edited Oct 16, 2011 at 13:45 slhck asked Oct 16, 2011 at 13:08 slhckslhck 38.9k33 gold badges160 silver badges218 bronze badges 2
  • Erm, what values do you want to be autopleted? you don't just pass a whole block of different kind of values to it.. Is it the label? is it the name? – dvir Commented Oct 16, 2011 at 13:17
  • @DvirAzulay Sorry, had to be more clear: Yes, for example, the label property should be shown to the user, and for example, geonames_uri could be the actual value behind it. – slhck Commented Oct 16, 2011 at 13:22
Add a ment  | 

3 Answers 3

Reset to default 5

The documentation (at the same link you posted) explains what is meant by the terms String-Array and Object-Array:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

So at the end of the day, it's either a String-Array: ["value1", "value2", ...] or an Object-Array:

[
  { label:"First Value", value:"value1" },
  { label:"Second Value", value:"value2" },
  ...
]

You can choose to either make the required server side changes to serialise the data to look appropriate, or map it client side, as in this example. Either way the end result should be one of the above formats.

So, for example, something like this:

function(data) {
response( $.map(data, function(item) {
  return {
  "label" : item.control_point.label,
  "value" : item.control_point.geonames_uri
  }
}));

This is something you'll want to do server-side, i.e. in Ruby on Rails. You could to this:

  • Give your model (ActiveRecord entity, whatever) a method toAutopleteResult that returns an Object with just the label and value properties.
  • In your controller (return_stuff_url?), loop through your result set, call toAutopleteResult() on them and put the results in an Array of sorts.
  • Convert the Array to JSON and return it.

I'm not a RoR developer, so I can't give you specific code. But this should be pretty easy to do in any OO language.

Edit: by the way, a JSON string array looks like this:

["String 1", "String 2", "String 3"]

And a JSON Object array would look like this:

[
    { "label" : "Label 1", "value": "Value 1" },
    { "label" : "Label 2", "value": "Value 2" }
]

You need something like this on the server

def my_autoplete_controller_method
  q = params[:term]
  records = Record.find_by_whatever q
  records.map { |record| {label: record.your_label, value: record.your_value} }
end

On the client (coffescript):

$find_field.autoplete
   source: /path_to_controller_method
发布评论

评论列表(0)

  1. 暂无评论