通过函数将PHP变量传递给JavaScript

时间:2012-08-25 21:09:44

标签: php javascript variables

我在数据库的字段中有以下文字:

Studied project requirements and documented specifications accordingly
Developed routing models for PDMS piping and associated equipment
Designed 3D illustrations for rough and final layout of piping routes and structures
Created elevated support system for complex piping structures to ensure proper functioning and safety
Provided detailed fabrication drawings
Performed stress and functional tests for new and existing designs
Upgraded existing layouts and structures as per the design and safety standards
Prepared plot plans and equipment layout
Developed isometric drawings, general arrangement drawings and support detail drawings

我通过变量(即$text)将其从数据库中取出,然后通过javascript函数function(text)对其进行解析,以便将文本发布到表单textarea字段中进行编辑。

但是当我点击按钮运行该功能时,它什么也没做。如果文本较小,则可以正常工作。 javascript变量的字符是否有限制?

PHP代码:

<?
$var = mysql_fetch_row($query);
$text=$var['cool'];

echo "<a onclick=\"func($text)\">button</a>";
?>

<script>
function func(text) {   
        $('<div>cool: '+text+'</div>').fadeIn('slow').appendTo('.somediv');
}
</script>

2 个答案:

答案 0 :(得分:4)

您需要对参数进行编码:

$text = htmlspecialchars(json_encode($var['cool']));

也就是说,从长远来看,其他解决方案可能会更好,因为元素已经在页面中的正确位置。这取决于你想用它做什么。

编辑:逃避可能并不完美。请广泛测试。

答案 1 :(得分:1)

我会这样做:(因为javascript限制中的文字)

<?php
    $var = mysql_fetch_row($query);
    $text=$var['cool'];

    echo "<div id=\"hiddendiv\" style=\"display:none\">".$text."</div><a onclick=\"func()\">button</a>";
?>

<script type="text/javascript">
function func(text) {   
    $('#hiddendiv').fadeIn('slow').appendTo('.somediv');
}
</script>