简体   繁体   English

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

[英]Include PHP inside JavaScript (.js) files

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 .php file containing the PHP function in the .js file?我是否需要在.js文件中“包含”包含 PHP 函数的.php文件?
  • 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 ).例如,假设我有一个名为 myLib.php 的文件,其中包含一个名为myFunc的函数,该函数接受两个参数( param1param2 )。 Then I have a .js file containing a function called myJsFunc .然后我有一个.js文件,其中包含一个名为myJsFunc的函数。 How would a call the myFunc (PHP) from within the myJsFunc (JavaScript function)?如何从myJsFunc (JavaScript 函数)中调用myFunc (PHP)? Wouldn't I need to include the PHP file somehow in the .js file?我不需要在.js文件中以某种方式包含 PHP 文件吗?

7 years later update: This is terrible advice. 7 年后更新:这是一个糟糕的建议。 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.如果您只需要将变量从 PHP 传递到 javascript,您可以使用 javascript 在 php/html 文件中添加一个标签。

<script type="text/javascript">
    var phpVars = <?php echo json_encode($vars) ?>;
</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">
    // assume each element of $arrayWithVars has already been json_encoded
    functionOne(<?php echo implode(', ', $arrayWithVars); ?>);

    functionTwo(<?php echo json_encode($moreVars) ?>, <?php echo json_encode($evenMoreVars) ?>);
</script>
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.危险:这将允许客户端潜在地看到您的 PHP 文件的内容。 Do not use this approach if your PHP contains any sensitive information (which it typically does).如果您的 PHP 包含任何敏感信息(通常会这样做),请不要使用这种方法。

If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file.如果您必须使用 PHP 生成 JavaScript 文件,那么请使用纯 PHP 生成整个 JS 文件。 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.您可以使用普通的 .PHP 文件以与通常输出 html 完全相同的方式来完成此操作,不同之处在于使用 PHP 的 header 函数设置正确的标头,以便将正确的 mime 类型返回给浏览器。 The mime type for JS is typically " application/javascript " JS 的 mime 类型通常是“ application/javascript

PHP and JS are not compatible; PHP和JS不兼容; you may not simply include a PHP function in JS.您可能不会简单地在 JS 中包含一个 PHP 函数。 What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.您可能想要做的是从 JavaScript 发出AJAX请求并使用 PHP 发送JSON响应。

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

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 插入您页面上的某个位置。

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.实际上,实现此目的的最佳方法是在 .php 中编写 javascript 并在单独的文件中使用 jquery 以使用 Jquery 获取脚本文件或 jquery 加载使用 php include 函数在 javascript 将存在的文档中。 Essentially this is how it will look.基本上这就是它的外观。

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.在主 html 页面中,将静态文件作为常规 js 文件调用。 Calling the static js file will force load the dynamic data from the server.调用静态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.我相信这回答了许多希望混合使用 php 和 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.您也可以绕过第二个文件并在主 html 页面上简单地使用 php 的包含,您只需在主页面上公开您的 javascript。 For performance that is up to you and how you want to handle all of that.性能取决于您以及您希望如何处理所有这些。

You can't include server side PHP in your client side javascript, you will have to port it over to javascript.您不能在客户端 javascript 中包含服务器端 PHP,您必须将其移植到 javascript。 If you wish, you can use php.js , which ports all PHP functions over to javascript.如果您愿意,可以使用php.js ,它将所有 PHP 函数移植到 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.您还可以创建一个新的 php 文件,该文件返回调用您的 PHP 函数的结果,然后使用 AJAX 调用该文件以获取结果。

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.因为 Javascript 在浏览器、客户端和 PHP 在服务器端执行,所以您需要的是AJAX - 本质上,您的脚本向 PHP 脚本发出 HTTP 请求,传递任何必需的参数。 The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call.该脚本调用您的函数,并输出结果,最终由 Ajax 调用获取。 Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!通常,您不会同步执行此操作(等待结果)- AJAX 中的“A”代表异步!

You can make a double resolution of file: "filename.php.js" in this way.您可以通过这种方式对 file: "filename.php.js" 进行双重解析。 PHP generates JS in this file. PHP 在这个文件中生成 JS。 I got all parameters from DB.我从数据库中获得了所有参数。 This worked for me on xampp.这在 xampp 上对我有用。

There is not any safe way to include php file into js .没有任何安全的方法可以将php文件包含到js

One thing you can do as define your php file data as javascript global variable in php file.您可以做的一件事是define php 文件数据define php 文件中的javascript global variable for example i have three variable which i want to use as js.例如我有三个我想用作 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 use it directly in your js file wherever you want to use.在您想要使用的任何地方直接在您的js file use它之后。

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.如果您有任何不想公开显示的关键数据,那么您可以使用 js 加密数据。 and also get original value of it's from js so no one can get it's original value.并且还从 js 中获取它的原始值,因此没有人可以获得它的原始值。 if they show into publicly.如果他们公开露面。

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 中的标准方法。

Instead of messing with generic php-handlers do a 1-file exception using a rewrite:不是使用通用的 php 处理程序,而是使用重写来执行 1-file 异常:

Rename the .js-file to .php and rewrite the request to make it responde to a .js request.将 .js 文件重命名为 .php 并重写请求以使其响应 .js 请求。 If the file is served by apache;如果文件由 apache 提供; add in .htaccess:添加.htaccess:

RewriteEngine on
RewriteRule myjsfile\.js myjsfile.php [L]

Secondly make the .php-file pretend to be a js-file.其次让 .php 文件假装是一个 js 文件。 Inside the php-file start the file with:在 php 文件中,用以下命令启动文件:

<?php header('Content-Type: application/javascript'); ?>

Et voilà, you can now use php-tags in your ".js"-file.等等,您现在可以在“.js”文件中使用 php-tags。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM