简体   繁体   中英

Use PHP variable in Javascript/jQuery

Why can't I use a calculated number, from php in jQuery?

I've tried this:

<div id="time">
    <? echo until();?>
</div>
var until = $("#time").html();

And

var until = <? echo until();?>;

But no one works D:

EDIT: The calculated number will be 472541, and the function:

<?
/**
* @desc Time until tuesday
* @param string Time format
* @return string timestamp
*/
function until($format = ""){
    $now = strtotime("now");
    $nextTuesday = strtotime("-1 hour next tuesday");
    $until = $nextTuesday - $now;
    if(empty($format)){
        return $until;
    }else{
        return date("$format",$until);
    }
}

?>

EDIT EDIT: Don't know what just happend, but it seems to work now:O:D Thanks a lot, everyone:D

The way I have been pulling PHP values from something like this into a variable is to make a new attribute in the DIV, something like

<div id="time" value="<?= until(); ?>">

</div>

then, by using JQuery, I can pull the variable by saying

var until = $('#time').attr(value);

Did you try it inside a script block, like so:

<script type="text/javascript">
/* <![CDATA[ */

    var until = <?php echo until();?>;
    alert(until);

/* ]]> */
</script>

can you try this

  <? $output =until();  echo $output?>

var until = <? echo $output ?>;

If you want to echo out the results of the until function, the function would have to actually return something. The following would work perfectly.

function until() {
    return '1';
}

<script type="text/javascript">
    var until = <?php echo json_encode(until()); ?>;
</script>

Note the use of json_encode(). While not necessary in this case, since it'd just output a '1'. using json_encode in general is a good idea, as it guarantees that whatever's coming out of PHP will be syntactically valid Javascript. It's very easy to generate Javascript on the fly that contains syntax errors, which will kill the rest of your script immediately.

First things first, you shouldn't be using shorthand <?php?> tags, it's not recommended. And second, I can't trace your problem, really.

http://codepad.viper-7.com/ufrfYR

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