如何将PHP变量传递给内联javascript函数?

时间:2013-11-13 01:12:00

标签: javascript php html

<div id="test" onclick="someFunction('<?=$some_id[1]?>', this);"><span ></span></div>

我正在尝试将PHP变量传入内联javascript函数;但是当此函数执行onclick时,它会抛出错误(Firebug控制台):

SyntaxError: unterminated string literal

someFunction('

3 个答案:

答案 0 :(得分:0)

我这样做的方法就是将它编码为json:

echo "someFunction(".htmlentities(json_encode($some_id[1]), ENT_QUOTES).", this);";

或者,如果您在html上下文中:

someFunction(<?php echo htmlentities(json_encode($some_id[1]), ENT_QUOTES); ?>, this);

json_encode将从各种数据类型中生成正确的javascript字符串,包括字符串,数字等。然后在向html添加任何内容时应始终使用htmlentities以确保引号不会破坏该输出。

请注意,我在字符串中添加引号 - 如果需要,json有自己的引号。

答案 1 :(得分:0)

您确定可以在托管服务上使用PHP短标签吗?

为了测试我会尝试:

<div id="test" onclick="someFunction('<?php echo $some_id[1]; ?>', this);"><span></span</div>

“someFunction”是否期望第一个变量的字符串或整数?如果它需要整数,你可能不需要变量周围的单引号。

这是假设$ some_id [1]包含一个整数值。

答案 2 :(得分:-2)

唯一可以直接传递给事件的是Event Object,这是不使用内联JavaScript的另一个原因。当然,你的PHP必须先编写,否则你应该研究一下AJAX解决方案。你的代码看起来应该更像:

  <script type='text/javascript'>
    var doc = document;
    function E(e){
      return doc.getElementById(e);
    }
    var tst = E('test');
    function anotherFunc(arg1, element){
      // do stuff here
    }
    tst.onclick = function(){
      anotherFunc('<?=$some_id[1];?>', this);
    }
  </script>
</body>
</html>
相关问题