views:

44

answers:

2

I am using getJson to pull in some info onto the page

$('#request_song').autocomplete({
  serviceUrl: '<%= ajax_path("trackName") %>',
  minChars:1,
  width: 300,
  delimiter: /(,|;)\s*/,
  deferRequestBy: 0, //miliseconds
  params: { artists: 'Yes' },
onSelect: function(value, data){
    // alert('You selected: ' + value + ', ' + $('#request_artist').val()); 
        $.getJSON('/get_events', function(data) {
                    $(data).each(function(key, value) {
                        console.log(value);
                    });
                });

    },
});

The json will have the name of the event and the city and date

I need to make a have a div that is on the page have the values from the json like

<div id="event_data">

//table info from json 
+1  A: 

Put markup in the argument to $() to create an element from it. Use values in a {} lookup to set attributes and text content (in jQuery 1.4). eg. something like:

$('#event_data').append(
    $('<div class="event"/>', {id: 'event_'+key}).append(
        $('<span class="event-name"/>', {text: value.name})
        $('<span class="event-city"/>', {text: value.city})
        $('<span class="event-date"/>', {text: value.date})
    )
);

Don't try to stick it together yourself ($('<span>'+value.name+'</span>')) or you'll have HTML-encoding issues and probably cross-site-scripting security holes.

bobince
+1  A: 

I'm guessing your response looks something like this...

var data = [{
  "event": "Birthday"
  "name": "John Doe",
  "city": "Sunnyvale",
  "date": "04/07/1982"
},{
  ...
}]

If you use $('<div />') or $('<div></div>') to create new elements, jQuery will use regex before creating the element which for obvious reasons will slow you down if you're dealing with large data sets.

For performance use:

var div = $(document.createElement('div'));

or keep it simple...

var div = document.createElement('div');

For performance use standard for loop, not $.each, and cache the length:

var container = $("#event_data");

for(var i = 0, k = data.length; i < k; i++){
  var event = $(document.createElement('div')),
      name = $(document.createElement('span')),
      city = $(document.createElement('span')),
      date = $(document.createElement('span'));

  // add id to event wrapper, if undefined generate random ID to avoid conflicts
  event.attr('id', 'event_'+data[i].event || Math.floor(Math.random()*100));

  // add each item, if undefined then insert empty text
  name.text(data[i].name || "").appendTo(event);
  city.text(data[i].city || "").appendTo(event);
  date.text(data[i].date || "").appendTo(event);

  // append & appendTo do exactly the same thing, markup preference
  container.append(event);
}

If you use text() the value will be treated as just that, text only, and will not be executed. If you use html() you'll have XSS issues.

Hopefully this helps and is what you're looking for.

Kieran