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

标签 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

I'm fetching it out of the database through a variable (i.e. $text) and then parsing it through a javascript function function(text) in order to post the text into a form textarea field for editing.

But when I click the button to run the function, it doesn't do anything. If the text is smaller it works fine. Is there any limit to the characters of a javascript variable?

PHP code:

<?
$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>

最佳答案

您需要对您的参数进行编码:

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

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

编辑:转义可能并不完美。请广泛测试。

关于php - 通过函数将 PHP 变量传递给 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12125679/

相关文章:

java - 声明一个全局变量,或者在每个类中声明多次

php - "prototype"的项目 "Array"不存在

php - PHP Comet 聊天系统的可扩展性问题

javascript - jquery 和 jquery UI 有什么区别?

javascript - 如何使用 jQuery 在点击时复制 div?

jquery - 使用 jquery $.post() 返回多个值

javascript - 是否可以使用字符串变量来引用 Javascript 中的元素?

php - 使用DOMDocument和DOMXPath类从网站中检索类别

php - 如何通过 "hint"浏览器将动态图像保存到磁盘的文件名?

javascript - 如何在 UFT 中模拟键盘输入事件