javascript 在 js 文件中包含 php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11429952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:11:42  来源:igfitidea点击:

include php in a js file

phpjavascriptinclude

提问by samuraiseoul

Possible Duplicate:
Parse a JavaScript file through PHP

可能的重复:
通过 PHP 解析 JavaScript 文件

I have some pretty long string variables in javascript that I instantiate in a .js file that way I can use them in multiple files, and also just so it doesn't muddle up the pages by being super long. However, I want to echo out some php into the .js file (so I can use a filepath specified in my php) and put it into the variable.

我在 javascript 中有一些很长的字符串变量,我在 .js 文件中实例化了它们,这样我就可以在多个文件中使用它们,而且它不会因为超长而混淆页面。但是,我想将一些 php 回显到 .js 文件中(这样我就可以使用我的 php 中指定的文件路径)并将其放入变量中。

I know that if it was in a normal html page I could just do <?php echo "foo"; ?>and it would work allright. But, in the js file it seems to ignore it. The js file currently instantiates a variable and an associative array that store html forms so I can put them on the page depending on some user input.

我知道,如果它是在一个普通的 html 页面中,我就可以这样做<?php echo "foo"; ?>,它会正常工作。但是,在 js 文件中它似乎忽略了它。js 文件当前实例化了一个变量和一个存储 html 表单的关联数组,因此我可以根据某些用户输入将它们放在页面上。

I need to echo out the php file path onto the action part of the form. THe reason for doing this is so I only have to change the file path once if I go back and modify my code. However the js file will either stick the actual text () in my variable, or the form won't load.

我需要将 php 文件路径回显到表单的操作部分。这样做的原因是,如果我回去修改我的代码,我只需要更改一次文件路径。但是,js 文件要么将实际文本 () 粘贴到我的变量中,要么无法加载表单。

Any help would be appreciated and if you need some more info, feel free to ask. Thanks alot!

任何帮助将不胜感激,如果您需要更多信息,请随时询问。非常感谢!

回答by Jeffrey Monte

change the file extension of your javascript file to .php and use that file instead example

将 javascript 文件的文件扩展名更改为 .php 并使用该文件代替示例

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

Also set the correct header on top of the file using

还使用在文件顶部设置正确的标题

<?php
    header("Content-type: text/javascript");
?>

回答by Debugger

Forcetype your js file as php , in your .htaccess file.
Something like this ,

在您的 .htaccess 文件中,将您的 js 文件强制输入为 php 。
像这样的东西,

<Files filename.js>
SetHandler application/x-httpd-php
ForceType application/x-httpd-php
</files>

回答by Max

It might help you 1. make .inc or php file 2. define class and function 3. write the js inside php function like

它可能对你有帮助 1. 制作 .inc 或 php 文件 2. 定义类和函数 3. 在 php 函数中编写 js,如

<?php
   class abc
   {
      public function sum()
      {
?>
        //your js here
<?php

      }

}
?>
  1. include this file in your required file
  2. create object and call the function
  1. 将此文件包含在您所需的文件中
  2. 创建对象并调用函数