简体   繁体   English

将简单的PHP代码包含到Javascript中

[英]Including simple PHP code into Javascript

How do I make this work? 我该如何工作? I've googled and even saw some examples here on Stackoverflow which show this kind of coding, but it doesn't work for me. 我已经搜索过Google,甚至在Stackoverflow上看到了一些显示这种编码的示例,但是它对我不起作用。

<script type="text/javascript">
  var infoClass = "";
  infoClass = <?php echo('test'); ?>;
  alert(infoClass);
</script>

The alert box displays empty box. 警报框显示一个空框。

Your resulting JS code will be: 您生成的JS代码将是:

infoClass = test;

As there's no variable test , this won't work right. 由于没有变量test ,因此无法正常工作。 You need to wrap it in quotes, just like any other string: 您需要像其他字符串一样将其用引号引起来:

<script type="text/javascript">
  var infoClass = "";
  infoClass = '<?php echo('test'); ?>';
  alert(infoClass);
</script>

You can also use json_encode() , which may be handy for more complicated situations where you're echoing out arrays, objects, etc.: 您还可以使用json_encode() ,它在回显数组,对象等更复杂的情况下可能会很方便:

infoClass = <?php echo json_encode('test'); ?>;

Make sure your code is in a .php file, or inside a file that has an extension that will be parsed by PHP. 确保您的代码在.php文件中,或者在文件扩展名为PHP的文件中。

Also make sure the printed content will be inside of a string ( "" ) 同时确保打印的内容在字符串(“”)内

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

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