0

I return an JSON array from PHP file with 200 ID's. (ID : number). I would like to just have 18 of theese ID's so that i send only 18 ID's to a new PHP file, then after 2 seconds, i would like to send the next 18 ID's of the JSON to the new PHP file as well, until there are no more ID's in the JSON array to send.

    $.get('get.php?randomize=1', function(data) {

        var json = data;

        $("#wallpaper").load('get_random.php?json_18=' + encodeURI(data), hideLoader());    

    });

As you see, i have stored the JSON in a variable called json. But i dont know how to split it up for each 18 ID's. I have read about .each function in jQuery, but i don't understand it well. I was hoping someone could help me.

3
  • Instead of splitting like that, why not use the standard offset / numResuts methodology? Commented Apr 29, 2012 at 16:56
  • Never even heard of that. What is it? Is there any good place to start reading about it? Commented Apr 29, 2012 at 17:02
  • You would change your callable to something like, get.php?randomize=1&offset=0&numResults=18. Your offset would increment each time, returning the next 18, and so on. Commented Apr 30, 2012 at 18:26

3 Answers 3

2

http://jsfiddle.net/2bZHP/4/:

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var spliceAt= 5;
var trigger = setTimeout(function() {
  var toSend;
  if(data.length>spliceAt)
  {
        var left= data.slice(0,spliceAt);
        var right = data.slice(spliceAt);
        data = right;
        toSend = left;
        setTimeout(arguments.callee, 2000);
  }
  else
  {
      toSend = data;
  }
  //$("#wallpaper").load('get_random.php?json_18=' + encodeURI(toSend), hideLoader());
  alert(toSend);
}, 2000);​
Sign up to request clarification or add additional context in comments.

Comments

1
$.get('get.php?randomize=1', function(data) {

   var json = data;
   for(i=0;i<n;i++)
   {
      setTimeout("$('#wallpaper').load('get_random.php?json_18=' + encodeURI(json.slice(i*18,(i*18)+18)), hideLoader());", i*20);
   }    

});

& check it out, maybe some error with syntax of setTimeout, didn't check it.

Comments

1

From jQuery documentation:

$.each([52, 97], function(index, value) { 
  alert(index + ': ' + value); 
});

will show:

0: 52
1: 97

So, the function iterates over each element, and applies a function to each one, passing the item index in the array and the item itself.

You can use slice() function in this way:

var taken = 0, step = 18;
var subset18;
while (taken < json.length) {
    subset18 = json.slice(taken, taken + step);
    taken += step;
    // do something with subset18
}

http://www.w3schools.com/jsref/jsref_slice_array.asp

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.