简体   繁体   中英

construct javascript from array in php

I have set up my site to use the gitter popup system. The javascript look like this:

$(document).ready(function(){
    setTimeout(function() {
        $.gritter.add({
            title: 'Welcome!',
            text: 'This appears to be your first time playing. Blablabla',
            time: '25000'
        }); 
    }, 500);                        
    setTimeout(function() {
        $.gritter.add({
            title: 'Walkthrough',
            text: 'A walkthrough was setup ...',
            time: ''
        }); 
    }, 30000);          
    setTimeout(function() {                         
        $.gritter.add({
            title: 'You got mail',
            text: 'You have received a message from x ',
            time: ''
        }); 
    }, 36000); 

This is an example of 3 popups. what I want to do is have arrays like this:

    $popup_title[0] = "Welcome!"; 
    $popup_text[0] = "This appears to be ..."); 
    $popup_time[0] = 25000;

        $popup_title[1] = "Walkthrough"; 
        $popup_text[1] = "A basic blabla ..."); 
        $popup_time[1] = "";

And loop through this arrays (if they aren't not empty) and construct the javascript based on the arrays.

something like this should do the job

<?php
$popups = array();
foreach ( $popup_title as $key => $title )
{
    $popups[$key] = new stdClass();
    $popups[$key]->title = $title;
}
foreach ( $popup_text as $key => $text )
{
    $popups[$key]->text = $text;
}
foreach ( $popup_time as $key => $time )
{
    $popups[$key]->time = $time;
}
?>
<script type="text/javascript">
$(document).ready(function(){
    <?php foreach ( $popups as $popup ): ?>
    setTimeout(function() {
        $.gritter.add(<?php echo json_encode($popup);?>);
    }
    <?php endforeach; ?>
}
</script>

只需回显PHP创建的JavaScript代码即可。

Using multiple arrays is a bit cumbersome, try using nested arrays, and make sure to escape your output in the javascript correctly (I'm not doing so below for clarity).

$popups = array(
    array( 'title' => 'First Title', 'text' => 'First Text', 'time' => 25000 ),
    array( 'title' => 'Second Title', 'text' => 'Second Text', 'time' => 2000 ),
);
echo "<script>";
foreach($popups as $idx=>$popup) {
    echo "setTimeout(function() { $.gritter.add({"
        ."title: '{$popup['title']}',"
        ."text: '{$popup['text']}',"
        ."time: ''"
    ."}); }, {$popup['time']}";    
}
echo "</script>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM