-2

我在使用 javascript 和 php 语言混合处理函数声明时遇到问题。

<script>
  //some JS code
  <?php getVideos() ?>
  //some JS code
</script>

<?php function getVideos()
      {
       //some code
      }
?>

问题是该函数是在 html 代码的另一部分中声明的,并且页面将无法工作,直到我不将它移到 JS 代码之前。有没有不需要移动php代码的解决方案?

编辑:我想确切地说我的 html 文件带有 php 扩展名(index.php),我可以正常访问整个文档中的 php 变量

4

3 回答 3

2

您必须使用 ajax 调用来调用函数。使用 jQuery.post 发布到您的 php 文件,并在服务器中使用 die 返回数据。PHP 在服务器端运行

示例:在 javascript 中:

<script>
    $(document).ready(function()
        {
            $.post(this.uri,{},function(){});
        });
</script>

在 php 中:

<?php 
if (isset($_POST))
{
    getVideos();
    die("1");

}
function getVideos()
{
    //some code
}

?>

于 2013-07-29T13:46:52.187 回答
1

我不认为你可以从 javascript 调用 php 函数。Javascript 无法运行 php 代码,因为 PHP 代码将在网页加载之前运行,而 javascript 在网页加载后运行。

无论如何,您仍然可以使用 ajax 运行外部 PHP 文件,如下所示:

$.ajax({
    url:'php/ajax_post.
    type: 'post',
    data: {function: "any_function"}
    success: function(data)
    {
        window.alert(data);
    }
});

在您的 PHP 文件中,添加一个 if 语句,如下所示:

if(isset($_POST['function']) && $_POST['function']=="any_function")
{
    //Run your function
}

这将运行您请求的功能,并提醒结果。

于 2013-07-29T13:46:05.237 回答
0

您可以使用 PHP 的include()函数从其他 PHP 文件中“导入”函数。

于 2013-07-29T13:46:07.150 回答