简体   繁体   English

将php变量传递给jQuery函数

[英]Pass a php variable to a jQuery function

I have searched and tried several different methods to pass a php $variable to a jQuery function. 我已经搜索并尝试了几种不同的方法来将php $ variable传递给jQuery函数。 I can pass a string simply by using myfunction("Hello");. 我可以简单地使用myfunction(“ H​​ello”);来传递字符串。 But if I try myfunction(); 但是,如果我尝试myfunction(); or myfunction($variable); 或myfunction($ variable); with or without quotes it fails to run. 带或不带引号的命令将无法运行。

function wholesection(val) {
    $("#whole-section").slideUp("fast", function () {
    });
    $('#label-cemetery').text("Section*");
    $('#poc').val(val);
}

The above works if I send a literal string enclosed in double quotes, using: 如果我使用以下命令发送用双引号引起来的文字字符串,则上述方法有效:

    <?php
        echo '<script>',
         'wholesection("Hello");',
         '</script>'
        ;
    ?>
</head>
<body>
    <?php
        $variable = "Hello";

        echo '<script>',
        'wholesection(' . $variable . ');',
        '</script>'
        ;
    ?>  

Or other similar variants do not work. 或其他类似的变体不起作用。

'wholesection($variable);',
'wholesection("$variable");',

You can pass it by echoing your php varriable in the script 您可以通过在脚本中回显您的php varriable来传递它

try below code : 试试下面的代码:

<?php
    $variable = "Hello";
?>
<script type="text/javascript">
    var simple = '<?php echo $variable; ?>';
</script>

Suppose your $variable has value "Hello" . 假设您的$variable值为"Hello"

Then this code: 然后这段代码:

echo 'wholesection('.$variable.');',

is rendrered in html like 在html中被rendrered像

wholesection(Hello);

See? 看到? You're passing Hello to a function. 您正在将Hello传递给函数。 Not "Hello" but Hello . 不是"Hello" ,但Hello And Hello is considered a javascript variable. Hello被认为是javascript变量。 I bet you don't have it. 我敢打赌你没有。

So, the fix is - add quotes: 因此,解决方法是-添加引号:

echo 'wholesection("'.$variable.'");',

which will be rendered as: 将呈现为:

wholesection("Hello");

 <?php $variable = "Hello"; if(true){ ?> <script> wholesection("<?php echo $variable?>"); </script> <? } ?> 

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

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