开发者

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开发者_JS百科, 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜