繁体   English   中英

从PHP函数调用Javascript函数

[英]Calling Javascript function from PHP function

以下是我在名为testOne.php的单个PHP文件中的testOne.php

<html>
<head>
     <script type="text/javascript">
          function testAlert(firstValue, secondValue)
          {
               alert ("Passed: "+firstValue+secondValue);
          }
     </script>
</head>
<body>
  ....
</body>
</html>

<?php
     function testPassedValues($One, $Two)
     {
        echo "<input type = \"button\" onclick = \"testAlert($One[2], $Two[2])\">Click Here!</input>";
     }

     $link = mysql_connect("localhost", "root", "");
     if (mysql_select_db("myDatabase", $link))
     {
         $result = mysql_query("SELECT * FROM MYTABLE");
         while($currRowOne = mysql_fetch_row($result) &&
               $currRowTwo = mysql_fetch_row($result))
         {
             testPassedValues($currRowOne, $currRowTwo);
         }
     }
?>

为了帮助理解,我调用JavaScript方法testAlert()从PHP函数testPassedValues() 但是,我不确定问题出在哪里,因为通话不成功。 在Mozilla(Firebug)中,没有发现任何问题,在Chrome-> Developer Tools中,我在控制台中收到错误Uncaught Syntaxerror: Unexpected token ILLEGAL

有人可以在这里帮助我解决根本原因吗?

我认为您不完全了解JavaScript和PHP的执行位置和方式。

PHP在服务器上运行。 它生成一个HTML页面(可能包含JavaScript),然后将其发送给客户端。 PHP现在完成。

然后,客户端的Web浏览器运行JavaScript。

要调试JavaScript问题,请查看客户端实际看到的网页。 如果Firebug报告了问题,那就在那里。

$One[2]$Two[2]的值很可能是字符串,因此生成的HTML为:

<input type = "button" onclick = "testAlert(string one, string two)">Click Here!</input>

这显然是无效的javascript。

将参数用引号引起来:

echo "<input type = \"button\" onclick = \"testAlert('$One[2]', '$Two[2]')\">Click Here!</input>";

您还应该正确地为HTML和JavaScript转义$One[2]$Two[2]值,以便在字符串包含撇号时不会引入XSS缺陷或错误。 我将由您自己决定。

暂无
暂无

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

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