How can I display the line items received by json depending on the date and time they were displayed?

I have a database, and I store the text there, its duration and the time when it should appear on the web page.

The php result is as follows:

{"text_content":"dgsgdsgds","text_duration":"15","start_time":"2015-09-28 23:11:15"},{"text_content":"dgsgdsgds","text_duration":"15","start_time":"2015-09-28 23:11:30"},{"text_content":"gdsgdsgds","text_duration":"15","start_time":"2015-10-01 14:00:00"} 

I have a jquery script that retrieves data from a database and displays it on the screen:

 var results =[]; var cursor = 0; function myFunction () { $.getJSON('list2.php', function(json) { results = json; cursor = 0; // Now start printing printNext(); }); } function printNext(){ if(cursor == results.length){ // Reset the cursor back to the beginning. cursor = 0; } // Print the key1 in the div. //$('#mydiv').html(results[cursor].key1); $('#mydiv').hide('fast', function(){ $('#mydiv').html(results[cursor].text_content); $('#mydiv').show('fast'); }); // Set a delay for the current item to stay // Delay is key2 * 1000 seconds setTimeout(function(){ printNext(); }, results[cursor].text_duration * 1000); // Advance the cursor. cursor++; } 

and now I wanted to add a function that is displayed on the screen only for the date received from the database, like start_time , but I'm not sure that this can be done only on jquery, without any further action, access to the server code. I tried to add some if statements:

 if(results[cursor].start_time == new Date()){ 

before you print it on the screen, but it didn’t help. could you help me? Thanks!

+5
source share
1 answer

Parse the json string using JSON.parse :

 var myObj = JSON.parse(results[0]); 

and compare your start_time :

 if (new Date(myObj.start_time) == new Date()) 

if you want to run your function at a specific time setTimeout :

 var diff = new Date(myObj.start_time).getTime() - new Date().getTime(); setTimeout(function() { $('#mydiv').hide('fast', function() { $('#mydiv').html(results[cursor].text_content); $('#mydiv').show('fast'); }); }, diff) 

or you can execute your function every 1000 ms using setInterval and stop it using clearInterval :

 function check() { if (new Date(myObj.start_time) == new Date()) { $('#mydiv').hide('fast', function() { $('#mydiv').html(results[cursor].text_content); $('#mydiv').show('fast'); }); clearInterval(myInterval); } } var myInterval = setInterval(check, 1000) 
+5
source

Source: https://habr.com/ru/post/1233083/


All Articles