如何将JavaScript放入JavaScript中? [英] How to put php inside JavaScript?

查看:157
本文介绍了如何将JavaScript放入JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过(但不能正常工作):

<?php  
  $htmlString= 'testing';
?>
<html>
  <body>
    <script type="text/javascript">  
      var htmlString=<?php echo $htmlString; ?>;
      alert(htmlString);
    </script>
  </body>
</html>

这是教程

推荐答案

试试这个:

<?php $htmlString= 'testing'; ?>
<html>
  <body>
    <script type="text/javascript">  
      // notice the quotes around the ?php tag         
      var htmlString="<?php echo $htmlString; ?>";
      alert(htmlString);
    </script>
  </body>
</html>

遇到类似这样的问题时,最好检查浏览器是否存在JavaScript错误。不同的浏览器有不同的显示方式,但寻找一个javascript控制台或类似的东西。另外,检查浏览器查看的页面来源。

When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.

有时初学者对字符串中的引号感到困惑:在PHP部分中,您指定了'testing' $ htmlString 。这会将一个字符串值放在该变量中,但该值中没有引号:它们仅用于解释器,因此他知道:哦,现在是一个字符串文字

Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing' to $htmlString. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.

这篇关于如何将JavaScript放入JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆