0

我试图将 php 代码放入 jquery 代码中,这是代码片段

html code

<div id="box">
hello
</div>

jQuery代码

    $(document).ready(function(){
        $('#box').click(function(e) {
     alert(<?php echo "hello";?>);

        });
      });

它在 mozilla 上运行良好,但是当我在 chrome 中运行它时显示错误

Uncaught SyntaxError: Unexpected token < 

那么有什么办法可以解决它

4

3 回答 3

3

您需要引用警报参数函数,如下所示:

代替

alert(<?php echo "hello";?>);

引用它

alert("<?php echo "hello";?>");

因为当你不引用它的时候

alert(hello); //here hello will behave like variable 

实时结果

但是当您使用引号时,它的 now字符串

alert("hello"); //here hello is string  

实时结果

于 2013-06-15T02:24:59.870 回答
0

您的警报消息本身没有用引号引起来,它应该是:

alert('<?php echo "hello";?>');

此外,确保包含 PHP 的 javascript 代码在您的实际 PHP 文件中 - 外部 Javascript 文件中的 PHP 代码根本不会被评估,这可能解释了关于“<”的奇怪错误

于 2013-06-15T02:26:28.617 回答
0

有点不清楚您是要提醒“Hello”还是要尝试将字符串插入 div,但无论哪种方式,您都不需要 PHP 来完成此操作:

$(document).ready(function(){
  $('#box').click(function(e) {
    alert("hello");
  });
});

或者

$(document).ready(function(){
  $('#box').click(function(e) {
    $(this).html("hello");
  });
});
于 2013-06-15T02:27:25.833 回答