简体   繁体   English

将这个数据库结果传递给javascript函数的正确方法是什么?

[英]What's the right way to pass this database result into a javascript function?

I am grabbing a string from a "title" field and passing it to an addText javascript function. 我正在从"title"字段中获取一个字符串,并将其传递给addText javascript函数。 I am having trouble passing the string properly though. 我在正确传递字符串时遇到了麻烦。 This---> 这个->

while ($row = mysql_fetch_assoc($part_result)){

 echo "<div id ='link' onclick = 'addText("$row['title']");'>" . $row['title'] ."</div>";

}

yields a syntax error. 产生语法错误。 Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';'

Thanks for your help! 谢谢你的帮助!

echo "<div id ='link' onclick = 'addText(\"".$row['title']."\");'>" . $row['title'] ."</div>";

You error is coming from the fact that you're not properly concatenating your static strings to your variables in all places. 您的错误是由于您没有在所有位置正确地将静态字符串连接到变量而引起的。

echo "<div id ='link' onclick = 'addText("$row['title']");'>" . $row['title'] ."</div>";

Should be 应该

echo '<div id="link" onclick="addText( \'' . $row['title'] . '\' );">' . $row['title'] . '</div>';

Also, since $row['title'] is being used inside of an HTML attr, it should be entitized to avoid quote collisions: 另外,由于在HTML属性中使用了$row['title'] ,因此应将其加密以避免引号冲突:

echo '<div id="link" onclick="addText( \'' .htmlentities( $row['title'], ENT_QUOTES ) . '\' );">' . $row['title'] . '</div>';

And for the cleanest code I'd use printf() : 对于最干净的代码,我将使用printf()

printf( '<div id="link" onclick="addText( \'%s\' );">%s</div>', htmlentities( $row['title'], ENT_QUOTES ), $row['title'] );

Try this : 尝试这个 :

echo '<div id="link" onclick="addText(\''.$row['title'].'\')">'.$row['title'].'</div>';

You don't need the ; 您不需要; after addText() addText()

Use json_encode to pass your title through. 使用json_encode传递标题。 This will encode it just in case you have single or double quotes (or any other bad character) in it. 万一您使用单引号或双引号(或任何其他坏字符),这将对其进行编码。

Also your error is coming from the variable itself. 另外,您的错误来自变量本身。 Since your are using double quotes, wrap your variable with curly brackets: 由于您使用的是双引号,因此请将变量用大括号括起来:

addText('{$row['title']}');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM