将php变量传递给外部javascript

时间:2013-02-13 23:49:22

标签: php javascript

如何将php变量传递到外部javascript文件中?我发现了很多关于这方面的问题,但无论如何我无法弄明白。

在HTML文件中,我有这个链接

<script type="text/javascript" src="myscript.php"></script>

这是我一直试图输出为javascript文件的myscript.php文件:

<?
Header("content-type: text/javascript");
?>

$(document).ready(function() {

$("#validate_form").validate({
    rules: {
        page_title: "required",
        seo_url: "required"
    },

    messages: {
        page_title: "<?=$page_title?>",
        seo_url: "<?=$seo_url?>"
    }
 }); 
});

1 个答案:

答案 0 :(得分:2)

使用查询字符串附加它们:

<script type="text/javascript" src="myscript.php?page_title=whatever&seo_url=whatever"></script>

<?
Header("content-type: text/javascript");
?>

$(document).ready(function() {

$("#validate_form").validate({
    rules: {
        page_title: "required",
        seo_url: "required"
    },

    messages: {
        page_title: "<?=$_GET['page_title'];?>",
        seo_url: "<?=$_GET['seo_url'];?>"
    }
 }); 
});