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 ?

4
  • 1
    "How to random each loop item" - Do you mean "How do I randomly sort/shuffle the "items" array?" Commented Mar 21, 2013 at 9: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. Commented Mar 21, 2013 at 9:13
  • can you post actual json data ? this looks like hard coded. Commented Mar 21, 2013 at 9:44
  • @nnnnnn yes i meam How do I randomly sort/shuffle the "items" array with limit 2 item , thx help! update json format Commented Mar 21, 2013 at 10:14

1 Answer 1

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.