简体   繁体   English

在Javascript中嵌入PHP无效

[英]Embedding PHP in Javascript doesn't work

I've got this javascript code: 我有以下JavaScript代码:

$(document)
   .load(function(){
      $.post(
          'result_source.php?term='+<?php echo $_REQUEST['term']; ?>
        );alert('abc123');
});

and it doesn't alert('abc123');. 并且不会发出警报('abc123');。 If I remove the 如果我删除

+<?php echo $_REQUEST['term']; ?>

it does alert('abc123'). 它确实会发出警报('abc123')。

Thanks 谢谢

You need to take the PHP part out of the concatenation. 您需要将PHP部分排除在串联之外。 The PHP is effectively pasted in to the javascript page before it is processed, so unless your $_REQUEST['term'] is the name of a javascript variable you are using, it will cause errors. PHP在处理之前已有效粘贴到javascript页面中,因此,除非$_REQUEST['term']是您正在使用的javascript变量的名称,否则它将导致错误。

Change it to: $(document).load(function(){$.post('result_source.php?term=<?php echo $_REQUEST['term']; ?>');alert('abc123');}); 更改为: $(document).load(function(){$.post('result_source.php?term=<?php echo $_REQUEST['term']; ?>');alert('abc123');});

Bear in mind this won't work inside external javascript files, unless you create an .htaccess or something to configure the server so it parses .js files as PHP before outputting to the browser 请记住,除非您创建了.htaccess或用于配置服务器的内容,否则它将无法在外部javascript文件中运行,以便在将其输出到浏览器之前将.js文件解析为PHP。

PHP will not run in an external JavaScript file unless you create a .htaccess file or configure the server so it parses .js files as PHP before outputting to the browser. 除非您创建.htaccess文件或配置服务器,否则PHP将不会在外部JavaScript文件中运行,以便在将其输出到浏览器之前将.js文件解析为PHP。

If you put that in a file(with a .php extension), in <script> tags, it will work, though. 如果将其放在<script>标记的文件(扩展名为.php )中,则可以使用。

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

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