-3

可能重复:
如何将 PHP 变量传递给 Javascript?

我需要以某种方式使这个函数接受参数。

索引.html

function dataOut(name2) {
    var names = name2.value;
    document.getElementById("output2").innerHTML = names;
    //even document.getElementById("output2").innerHTML= "blablabla"; 
    //just to show that it works
}

该函数将从以下位置调用:

dbase.php

...
echo "<td><a href='javascript:dataOut(this.value)'>" . $row['FirstName'] . "</a></td>";
...

我在显示表格时没有问题。该链接确实显示了它们各自的“$row['FirstName']”,它们是来自数据库的字符串。我尝试使用非参数函数:

function dataOut(){}
echo "<td><a href='javascript:dataOut()'>" . $row['FirstName'] . "</a></td>";

这些工作正常。

如果我尝试传递参数,该函数将不会做任何事情;即使我只想像函数的注释部分那样打印随机字符串。如果我将鼠标悬停在该表中创建的链接上,我会看到:

javascript:dataOut(firstname)
//where first name is the value of the $row['FirstName']

我尝试过的替代方案:

echo "<td><a href='javascript:dataOut(this.value)'>" . $row['FirstName'] . "</a></td>";
echo "<td><a href='javascript:dataOut($row['FirstName'])'>" . $row['FirstName'] . "</a></td>";
echo "<td><a href='javascript:dataOut('" . $row['FirstName'] .'")'>" . $row['FirstName'] . "</a></td>"; //this give me undefined variable error
echo "<td><a href='javascript:dataOut(". $row['FirstName']. ")'>" . $row['FirstName'] . "</a></td>"; // this no error

任何帮助,将不胜感激。此外,我也尝试过,这也<a onclick=dataOut ....>不起作用。

4

1 回答 1

2

You shouldn't try to create JavaScript strings by concatenating quotes and plain strings. Use json_encode() instead which is guaranteed to output a valid JavaScript expression:

echo "<td><a href='javascript:dataOut(".json_encode($row['FirstName']).")'>" . $row['FirstName'] . "</a></td>";

On a side-note, using javascript: urls is generally a bad idea. Better use onclick="dataOut(...); return false;" instead and use a useful href value or # if no proper URL for people without JavaScript exists. Of course it would be even better to register the event properly instead of using an inline event, and storing the data in a data- attribute but this would be even more off-topic here.

于 2012-06-09T00:12:33.087 回答