如何将变量从php传递给javascript

时间:2014-11-09 16:33:59

标签: javascript php jquery

如果我将一个硬编码的数值从php传递给javascript,那么一切都很完美。但是,如果我从变量传递数值,我会收到一个错误:

javascript文件(gallery.js)

function goto_anchor(id)
{
    var anchor = $("#anchor_" + id);

    $('html,body').animate({
        scrollTop: anchor.offset().top - 20
    }, 1200);
}

php文件

....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="js/gallery.js" type="text/javascript"></script><?php

$get_cat = 4;

if (isset($get_cat)) { ?>
    <script>
        $(document).ready(function() {
            goto_anchor(4); // this will work PERFECTLY!!!
            goto_anchor(<?php echo $get_cat; ?>); // this will NOT work !!!
        });
    </script><?php
} ?>

我需要在我的php中传递$ get_cat变量,而不是带符号的数值。怎么样 ?? 感谢

1 个答案:

答案 0 :(得分:0)

我之前遇到过这样的问题,无法填写

javascriptfunction(<?php echo $phpvirable ?>) 

导致错误的javascript函数内部;相反,根据您的代码,可以在使用它之前将其回显到javascript virable;

echo '<script> var get_cat = '.$get_cat.'</script>'; 

进入你的php

<?php   $get_cat = 4;  ?>

当然,您可以从表单提交事件向此页面的$ _REQUEST [&#39; cat&#39;]动态值中捕获您的php $ get_cat。然后你将它转换为javascript virable在函数中使用。

<?php
if(isset($getcat)):
echo '<script> var get_cat = '.$getcat.'</script>';
endif;
?> 
// javascript function read predefined javascript virable that confirm work.

// u also avoid using mixed php and javascript statements which looks messy
<script> 
    $(document).ready(function() {
         goto_anchor(get_cat); // this will work then.
    });
</script>