简体   繁体   English

在 Javascript/jQuery 中使用 PHP 变量

[英]Use PHP variable in Javascript/jQuery

Why can't I use a calculated number, from php in jQuery?为什么我不能使用 jQuery 中的 php 中的计算数字?

I've tried this:我试过这个:

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

And

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

But no one works D:但没有人工作 D:

EDIT: The calculated number will be 472541, and the function:编辑:计算出来的数字是 472541,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编辑编辑:不知道刚刚发生了什么,但它现在似乎可以工作了:O:D 非常感谢大家: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我将 PHP 值从类似的东西拉到变量中的方式是在 DIV 中创建一个新属性,例如

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

</div>

then, by using JQuery, I can pull the variable by saying然后,通过使用 JQuery,我可以通过说

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.如果您想回显直到 function 的结果,则 function 将不得不实际返回一些东西。 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().注意 json_encode() 的使用。 While not necessary in this case, since it'd just output a '1'.虽然在这种情况下没有必要,因为它只是 output 一个“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.通常使用 json_encode 是一个好主意,因为它保证从 PHP 出来的任何东西在语法上都是有效的 Javascript。 It's very easy to generate Javascript on the fly that contains syntax errors, which will kill the rest of your script immediately.动态生成包含语法错误的 Javascript 非常容易,这将立即杀死脚本的 rest。

First things first, you shouldn't be using shorthand <?php?> tags, it's not recommended.首先,您不应该使用简写<?php?>标签,不推荐。 And second, I can't trace your problem, really.其次,我无法追踪你的问题,真的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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