按下按钮时调用需要sn值的函数,但下面的代码与Chrome调试消息失败:
Uncaught ReferenceError: Telephony is not defined
电话是其中一种服务名称。
<html>
<head>
<title>someTitle</title>
<script>
function myF(varname) {
//I'll do here some other task with varname
console.log(varname);
}
</script>
</head>
<body>
<pre>
<?php
$sn='noname';
//here, the code to connect and select DB
while ($reg=mysql_fetch_array($registers))
{
echo "Service Name: ".$reg['sname']."<br>";
$sn = $reg['sname'];
echo "<button onclick="myF($sn)">Vote</button>";
echo "<hr>";
}
mysql_close($conexion);
?>
</pre>
</body>
</html>
是否有一个简单的解决方案?我的PHP服务器有PHP5
- 假设变量$sn是"Stack"。因此$sn是一个字符串,你需要传递这个变量
- 所以重写myF (sn) myF(",sn美元。")。
- 当你检查按钮,你可以看到myF('Stack')。
- 那么在javascript中你可以避免这个错误。
为什么需要双引号?
echo "<button onclick="myF($sn)">Vote</button>";
这样做:
echo '<button onclick="myF(''. $sn . '')">Vote</button>';
或者像这样处理sprintf
:
echo sprintf("<button onclick="myF('%s')">Vote</button>", $sn);
这样行吗?
echo "<button onclick="myF('$sn')">Vote</button>";
我尝试了一个简单的测试用例,没有任何MySQL。您可以在下面找到我使用的代码:
<?php
$sn='noname';
$registers = array(array('sname' => 'apple'), array('sname' => 'banana'), array('sname' => 'woodapple')); // Dummy "MySQL" Fetch Array (this might differ from what your 'while' loop receives)
foreach ($registers as $reg){ // In your case, a 'while' loop works.
echo "Service Name: ".$reg['sname']."<br>";
$sn = $reg['sname'];
echo "<button onclick="myF('$sn')">Vote</button>"; // Added Quotes.
echo "<hr>";
}
?>
提示:请避免使用mysql_*函数!它们被弃用了!
您需要像这样更改连接,
echo '<button onclick="myF("'.$sn.'")">Vote</button>';
我认为,当你传递PHP变量作为参数在onclick
按钮调用javascript function
事件,你的字符串中断,因为它没有引用。所以它需要被引用。我已经编辑的代码行,你需要编辑你的代码。所以试试这样写:
...
......
........
........
echo "<button onclick="myF("$sn")">Vote</button>";
.......
......
....