2

How to random each loop item and on ajax / json data in jquery ?

data.json

{
  "items" : [
    {
      "title" : "new1",
      "content" : "content1"
    },
    {
      "title" : "new2",
      "content" : "content2"
    },
    {
      "title" : "new3",
      "content" : "content3"
    },
    {
      "title" : "new4",
      "content" : "content4"
    }
  ]
}

jquery ajax get json

    $.ajax({
        url: 'data.json',
        type: 'get',
        dataType: 'json',
        async: false,
        success: function(data){
              $.each(data.items, function(index,item) {
               var template = '<p>' + item.title + '</p>' + item.content + '<br />'; 

                  $('html').append(template);
                  return index < 1 ; // set 2 item 
              });

        }
     });

How to random each loop item and on ajax / json data in jquery ?

komodo
  • 37
  • 2
  • 6
  • 1
    _"How to random each loop item"_ - Do you mean "How do I randomly sort/shuffle the `"items"` array?" – nnnnnn Mar 21 '13 at 09:12
  • here you have leave one curly brasses } in the code. so may be this will be the error. and why you want to return the value. do you know the return will through you out of loop. – Code Lღver Mar 21 '13 at 09:13
  • can you post actual json data ? this looks like hard coded. – Sangeeta Mar 21 '13 at 09:44
  • @nnnnnn yes i meam How do I randomly sort/shuffle the "items" array with limit 2 item , thx help! update json format – komodo Mar 21 '13 at 10:14

1 Answers1

1

Add ' and also close .each() add }); at the end of .each()

$.each(data.items, function(index,item) {
    var template = '<p>' + item.title + '</p>' + item.content + '<br />'; });

For Random

var random_index = Math.floor(Math.random()*data.length);
var item = data[random_index];
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90