繁体   English   中英

在while循环中使用php字符串作为javascript函数中的参数

[英]Using a php string as an argument in javascript function in a while loop

我正在尝试创建一个JavaScript函数,其中第一个参数是数字,第二个arg是字符串。 我的代码在下面,我在这里添加了注释以使其易于阅读。

while ($dbsearch = mysqli_fetch_assoc($run_query)) {

    //define 3 vables. Example $dbu = 'Bill.Gates'
    //Example $id = 123
    // example $func using the values above should say add(123,'Bill.Gates')

    $dbu = $dbsearch['Username'];
    $id = $dbsearch['PlayerID'];
    $func = "add(" . $id . ",'" . $dbu . "')";

    //this is a string to output the results of an SQL search. It is working fine. The 
    // $func is inserted toward the end in the submit button.

    echo "<tr><td>" . $id . "</td><td>" . $dbu 
    . "</td><td><input type='submit' id='PlayerAdded" . $id 
    . "' value='Add' onclick='" . $func . "'></input></td></tr>";
}

提交按钮的目的是在事件中添加玩家名称作为注册玩家。

我试过将$func变量更改为仅输出两个参数的$id ,并且可行,但是我无法获取它来输出字符串(人名)。

我该如何解决?

补充:对不起,如果我的问题不清楚。 我想知道如何获取add函数来接受字符串作为参数。 例如

add(123,'Bill Gates');

尝试注释此行:

// $func = "add(" . $id . ",'" . $dbu . "')";

然后在您的回声中:

echo "
<tr>
   <td>" . $id . "</td>
   <td>" . $dbu . "</td>
   <td>
       <input type='submit' id='PlayerAdded" . $id . "' value='Add' onclick='add(" . $id . ", \'" . $dbu ."\');' />
   </td>
</tr>";

您不是逃脱引号。

$dbsearch = array(array('Username' => 'First User', 'PlayerID' => 1),
                  array('Username' => 'Second User', 'PlayerID' => 2));

echo '<table>';
foreach ( $dbsearch as $db ) {

  $func = 'add(' . $db['PlayerID'] . ', \'' . $db['Username'] . '\')';
  echo '<tr>
          <td>' . $db['PlayerID'] . '</td>
          <td>' . $db['Username'] . '</td>
          <td><input type="submit" id="PlayerAdded' . $db['PlayerID'] . '" value="Add" onclick="' . $func . '"></td>
        </tr>';
}
echo '</table>';

?>

<script type="text/javascript">
  function add( id, name ) {
    document.write( 'Id: ' + id + ', Name: ' + name );
  }
</script>

暂无
暂无

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

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