在 JavaScript (.js) 文件中包含 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3241422/
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-08-23 03:49:28  来源:igfitidea点击:

Include PHP inside JavaScript (.js) files

phpjavascript

提问by GregH

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

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

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 文件中的一个 PHP 函数,该文件只包含一个 JavaScript 函数中的几个 PHP 函数。

  • Is that possible?
  • Would I need to "include" the .phpfile containing the PHP function in the .jsfile?
  • How would I do that?
    For example, say I had a file called myLib.php containing a function called myFuncthat takes two parameters (param1and param2). Then I have a .jsfile 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 .jsfile?
  • 那可能吗?
  • 我是否需要在.php文件中“包含”包含 PHP 函数的.js文件?
  • 我该怎么做?
    例如,假设我有一个名为 myLib.php 的文件,其中包含一个名为的函数myFunc,该函数接受两个参数(param1param2)。然后我有一个.js文件,其中包含一个名为myJsFunc. 如何myFuncmyJsFunc(JavaScript 函数)中调用(PHP )?我不需要在文件中以某种方式包含 PHP.js文件吗?

回答by sgrif

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

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

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.

如果您只需要将变量从 PHP 传递到 javascript,您可以使用 javascript 在 php/html 文件中添加一个标签。

<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>

回答by ammar

AddType application/x-httpd-php .js

AddHandler x-httpd-php5 .js

<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>

Add the above code in .htaccess file and run php inside js files

在.htaccess文件中添加上面的代码并在js文件中运行php

DANGER:This will allow the client to potentially see the contents of your PHP files. Do not use this approach if your PHP contains any sensitive information (which it typically does).

危险:这将允许客户端潜在地看到您的 PHP 文件的内容。如果您的 PHP 包含任何敏感信息(通常会这样做),请不要使用这种方法。

If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file. You can do this by using a normal .PHP file in exactly the same way you would normally output html, the difference is setting the correct header using PHP's header function, so that the correct mime type is returned to the browser. The mime type for JS is typically "application/javascript"

如果您必须使用 PHP 生成 JavaScript 文件,那么请使用纯 PHP 生成整个 JS 文件。您可以通过使用普通的 .PHP 文件以与通常输出 html 完全相同的方式来完成此操作,不同之处在于使用 PHP 的 header 函数设置正确的标头,以便将正确的 mime 类型返回给浏览器。JS 的 mime 类型通常是“ application/javascript

回答by NikiC

PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAXRequest from JavaScript and send a JSONresponse using PHP.

PHP和JS不兼容;您可能不会简单地在 JS 中包含一个 PHP 函数。您可能想要做的是从 JavaScript发出AJAX请求并使用 PHP发送JSON响应。

回答by Scot Bernard

A slightly modified version based on Blorgbeard one, for easily referenceable associative php arrays to javascript object literals:

一个基于 Blorgbeard 的稍微修改的版本,用于轻松引用关联 php 数组到 javascript 对象文字:

PHP File (*.php)

PHP 文件 (*.php)

First define an array with the values to be used into javascript files:

首先定义一个数组,其中包含要用于 javascript 文件的值:

<?php
$phpToJsVars = [
  'value1' => 'foo1',
  'value2' => 'foo2'    
];
?>

Now write the php array values into a javascript object literal:

现在将 php 数组值写入 javascript 对象文字:

<script type="text/javascript">
var phpVars = { 
<?php 
  foreach ($phpToJsVars as $key => $value) {
    echo '  ' . $key . ': ' . '"' . $value . '",' . "\n";  
  }
?>
};
</script>

Javascript file (*.js)

Javascript 文件 (*.js)

Now we can access the javscript object literal from any other .js file with the notation:

现在我们可以使用符号从任何其他 .js 文件访问 javscript 对象文字:

phpVars["value1"]
phpVars["value2"]

回答by Josiah

This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.

这有点棘手,因为 PHP 在服务器端进行评估,而 javascript 在客户端进行评估。

I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.

我会使用 JavaScript 内部的 AJAX 调用来调用您的 PHP 文件,然后使用 JS 将返回的 HTML 插入您页面上的某个位置。

回答by DEVPROCB

Actually the best way to accomplish this is to write the javascript in a .php and use jquery in a separate file to use the Jquery get script file or jquery load use php include function in the doc where the javascript will live. Essentially this is how it will look.

实际上,实现此目的的最佳方法是在 .php 中编写 javascript 并在单独的文件中使用 jquery 以使用 Jquery 获取脚本文件或 jquery 加载使用 php include 函数在 javascript 将存在的文档中。基本上这就是它的外观。

Dynamic Javascript File in a .php file extension - Contains a mixture of php variables pre processed by the server and the javascript that needs these variables in scripts.

.php 文件扩展名中的动态 Javascript 文件 - 包含由服务器预处理的 php 变量和脚本中需要这些变量的 javascript 的混合。

Static Js File - Using http://api.jquery.com/jquery.getscript/or http://api.jquery.com/load/

静态 Js 文件 - 使用http://api.jquery.com/jquery.getscript/http://api.jquery.com/load/

In the main html page call the static file as a regular js file. Calling the static js file will force load the dynamic data from the server.

在主 html 页面中,将静态文件作为常规 js 文件调用。调用静态js文件将强制从服务器加载动态数据。

some file.php 1:

一些 file.php 1:

<?php
$somevar = "Some Dynamic Data";
?>

$('input').val(<?php echo $somevar?>);

or simply echo the script such as

或者简单地回显脚本,例如

echo "$('input').val(".$somevar.");";

File 2:somejsfile.js:

文件 2:somejsfile.js:

$("#result").load( "file.php" );

File 3 myhtml.html:

文件 3 myhtml.html:

<script src="somejsfile.js"></script>

I believe this answer the question for many people looking to mix php and javascript. It would be nice to have that data process in the background then have the user have delays waiting for data. You could also bypass the second file and simply use php's include on the main html page, you would just have your javascript exposed on the main page. For performance that is up to you and how you want to handle all of that.

我相信这回答了许多希望混合使用 php 和 javascript 的人的问题。最好在后台处理该数据,然后让用户延迟等待数据。您也可以绕过第二个文件并在主 html 页面上简单地使用 php 的包含,您只需在主页面上公开您的 javascript。性能取决于您以及您希望如何处理所有这些。

回答by barbocc

You can make a double resolution of file: "filename.php.js" in this way. PHP generates JS in this file. I got all parameters from DB. This worked for me on xampp.

您可以通过这种方式对 file: "filename.php.js" 进行双重解析。PHP 在这个文件中生成 JS。我从数据库中获得了所有参数。这在 xampp 上对我有用。

回答by Himanshu

There is not any safe way to include phpfile into js.

没有任何安全的方法将php文件包含到js.

One thing you can do as defineyour php file data as javascript global variablein php file. for example i have three variable which i want to use as js.

您可以像define在 php 文件中一样作为php 文件数据做一件事javascript global variable。例如我有三个我想用作 js 的变量。

abc.php

abc.php

<?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>

After useit directly in your js filewherever you want to use.

之后use直接在js file你想要使用的任何地方。

abc.js

abc.js

function test(){
   alert('Print php variable : '+ abc +', '+number); 
}

function printArrVar(){
  alert('print php array variable : '+ JSON.stringify(mydata)); 
}

Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.

如果您有任何不想公开显示的关键数据,那么您可以使用 js 加密数据。并且还从 js 中获取它的原始值,因此没有人可以获得它的原始值。如果他们公开露面。

this is the standard way you can call php script data into js file without including js into php code or php script into js.

这是您可以将 php 脚本数据调用到 js 文件中而不将 js 包含到 php 代码中或将 php 脚本包含到 js 中的标准方法。

回答by Cristian Sanchez

You can't include server side PHP in your client side javascript, you will have to port it over to javascript. If you wish, you can use php.js, which ports all PHP functions over to javascript. You can also create a new php file that returns the results of calling your PHP function, and then call that file using AJAX to get the results.

您不能在客户端 javascript 中包含服务器端 PHP,您必须将其移植到 javascript。如果您愿意,可以使用php.js,它将所有 PHP 函数移植到 javascript。您还可以创建一个新的 php 文件,该文件返回调用您的 PHP 函数的结果,然后使用 AJAX 调用该文件以获取结果。

回答by Paul Dixon

Because the Javascript executes in the browser, on the client side, and PHP on the server side, what you need is AJAX- in essence, your script makes an HTTP request to a PHP script, passing any required parameters. The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call. Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!

因为 Javascript 在浏览器、客户端和 PHP 在服务器端执行,所以您需要的是AJAX- 本质上,您的脚本向 PHP 脚本发出 HTTP 请求,传递任何必需的参数。该脚本调用您的函数,并输出结果,最终由 Ajax 调用获取。通常,您不会同步执行此操作(等待结果)- AJAX 中的“A”代表异步!