在JavaScript(.js)文件中包含PHP [英] Include PHP inside JavaScript (.js) files

查看:95
本文介绍了在JavaScript(.js)文件中包含PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个JavaScript函数的JavaScript文件(扩展名 .js ,而不是 .html )。

I have a JavaScript file (extension .js, not .html) containing several JavaScript functions.

我想调用PHP文件中的一个PHP函数,其中只包含一个JavaScript函数中的几个PHP函数。

I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.


  • 这可能吗?

  • 我是否需要包含 .php 文件在 .js 文件中包含PHP函数?

  • 我该怎么做?
    例如,假设我有一个名为myLib.php的文件,其中包含一个名为 myFunc 的函数,它接受两个参数( param1 param2 )。然后我有一个 .js 文件,其中包含一个名为 myJsFunc 的函数。如何从 myJsFunc (JavaScript函数)中调用 myFunc (PHP)?我不需要在 .js 文件中以某种方式包含PHP文件吗?

  • Is that possible?
  • Would I need to "include" the .php file containing the PHP function in the .js file?
  • How would I do that?
    For example, say I had a file called myLib.php containing a function called myFunc that takes two parameters (param1 and param2). Then I have a .js file containing a function called myJsFunc. How would a call the myFunc (PHP) from within the myJsFunc (JavaScript function)? Wouldn't I need to include the PHP file somehow in the .js file?

推荐答案

7年后更新:这是一个糟糕的建议。请不要这样做。



如果你只需要将变量从PHP传递到javascript,你可以在php / html文件中使用javascript来标记开始于。

7 years later update: This is terrible advice. Please don't do this.

If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.

<script type="text/javascript">
    phpVars = new Array();
    <?php foreach($vars as $var) {
        echo 'phpVars.push("' . $var . '");';
    };
    ?>
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>

如果您正在尝试调用函数,那么您可以这样做

If you're trying to call functions, then you can do this like this

<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
    functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
    functionTwo(<?php echo $moreVars; ?>, <?php echo $evenMoreVars; ?>);
</script>

这篇关于在JavaScript(.js)文件中包含PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆