Javascript 用php代码调用javascript函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4333223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:57:00  来源:igfitidea点击:

Calling javascript function with php code

phpjavascript

提问by CentosUser

I am trying to call the Javascript function declared at the top in my php area. However its not working. Can anyone tell me the reason for it. Everything else is working except for this part. Please help me.

我正在尝试调用在我的 php 区域顶部声明的 Javascript 函数。但是它不起作用。谁能告诉我它的原因。除了这部分,其他一切都在工作。请帮我。

  <!doctype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
  <head>
  <title>AES (Rijndael) Encryption Test in JavaScript</title>
  <script src="aes-enc.js" type="text/javascript" language="JavaScript"></script>
  <script src="aes-dec.js" type="text/javascript" language="JavaScript"></script>
  <script src="aes-test.js" type="text/javascript" language="JavaScript"></script>
  <script type="text/javascript">

   function doDecryption()
            {
            document.write("Inside Javascript");
            var ct, key;

  ct = hex2s(<?php echo $myValue; ?>);
  document.write("Inside Javascript");
  document.write(ct);
 // key = hex2s(theForm.key.value);
 // theForm.plaintext.value = byteArrayToHex(rijndaelDecrypt(ct, key, "ECB"));


            }


  </script>
  </head>

  <body>
  <?php
  mysql_connect("localhost","root","");
  mysql_select_db("encryption") or die(mysql_error());
  $userId = $_POST['userId'];


  if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key'] == ""))
  {
     $query = mysql_query("select * from employee_details where id = '$userId'");                       if($row=mysql_fetch_assoc($query))
                {
                    echo '<tr>';
                    foreach($row as $value)
                    echo '<td>'.$value.'</td>';
                    echo '</tr>';
                }

            else { echo "No rows returned"; }}
    else if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key']))
        {

           $columname = "ciphertext";
           $tablename = "employee_details";



                function getField($field, $tbl_name, $condition)
            {

                $result = mysql_query("SELECT $field FROM $tbl_name WHERE id =  ".$condition);

                 return @mysql_result($result, 0);
            }

                $myValue = getField($columname,$tablename,$userId);

                echo "$myValue";
                [B]echo '<script type="text/javascript">
                    doDecryption();
                    </script>';[/B]
                echo "whats happening";
                //doDecryption();

        }

   ?>
  </body>
  </html>

回答by Quentin

$myValuedoesn't have a value when you try to use it in the JS.

$myValue当您尝试在 JS 中使用它时,它没有价值。

The PHP runs on the server, outputs an HTML document with embedded JavaScript, the document is sent to the client and then the JavaScript runs.

PHP 在服务器上运行,输出一个嵌入了 JavaScript 的 HTML 文档,该文档被发送到客户端,然后 JavaScript 运行。

If you don't know what value the JavaScript variable needs to have until the PHP gets to the end of the document, then you can't generate that part of the JS until then. You probably want to write it as an argument to the function call instead.

如果您在 PHP 到达文档末尾之前不知道 JavaScript 变量需要具有什么值,那么在此之前您无法生成 JS 的那部分。你可能想把它写成函数调用的参数。

Once you do that you have another problem — if your data is a string, then it needs to be quoted (and any matching quote marks inside it need to be escaped).

一旦你这样做了,你就会遇到另一个问题——如果你的数据是一个字符串,那么它需要被引用(并且它里面的任何匹配的引号都需要被转义)。

In a nutshell: PHP outputs text that might be processed as JS, it cannot call JavaScript functions(unless you start mixing extensions that can talk to Rhino/Spidermonkey/etc on the server).

简而言之:PHP 输出的文本可能会被处理为 JS,它不能调用 JavaScript 函数(除非您开始混合可以与服务器上的 Rhino/Spidermonkey/etc 通信的扩展)。

All that said, in this case, there doesn't seem to be any reason to use JavaScript in the first place and you would be better off moving all the logic to PHP.

尽管如此,在这种情况下,似乎没有任何理由首先使用 JavaScript,最好将所有逻辑移至 PHP。

Incidentally, your choice of Doctype will trigger Quirks mode in most browsers. This is almost always highly undesirable.

顺便说一句,您选择的 Doctype 将在大多数浏览器中触发 Quirks 模式。这几乎总是非常不受欢迎的。

A better choice would be:

更好的选择是:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

Or if you really want Transitional:

或者如果你真的想要过渡:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

回答by Gabriele Petrioli

Change you javascript function to take a parameter (the value of $myValue)

更改您的 javascript 函数以获取参数(的值$myValue

function doDecryption(param)

Then change the ct = hex2s(<?php echo $myValue; ?>);to ct = hex2s(param);

然后更改ct = hex2s(<?php echo $myValue; ?>);ct = hex2s(param);

Last, you need to pass the $myValuephp variable to the javsacript function function and you can do this when you call it

最后,您需要将$myValuephp 变量传递给 javsacript 函数函数,您可以在调用它时执行此操作

echo '<script type="text/javascript">
                doDecryption( '.$myValue;.');
                </script>';

if you $myValuevariable is a stirng, then you should add quotes around it when feeding it to javascript

如果你的$myValue变量是一个stirng,那么你应该在将它提供给javascript时在它周围添加引号

echo '<script type="text/javascript">
                doDecryption( "'.$myValue;.'");
                </script>';

回答by Mark At Ramp51

Can you clarify the question? If the question is: can you call a client side javascript function, at runtime in your server side PHP code? the answer is no.

你能澄清这个问题吗?如果问题是:您可以在运行时在服务器端 PHP 代码中调用客户端 javascript 函数吗?答案是不。

if you ran a nodeJS server it's possible to host the javascript server side and execute the function calls as long as the javascript code resides somewhere that nodejs can execute it.

如果您运行 nodeJS 服务器,则可以托管 javascript 服务器端并执行函数调用,只要 javascript 代码驻留在 nodejs 可以执行它的某个地方。

Overall though, the use case is confusing to me. I am guessing that an application that was originally designed to do decryption client side in the browser does so because the server does not have the keys to perform the decryption. So if this was an application that someone else wrote and you are trying to make changes to, you will want to make sure that you actually have the keys you need server side to perform the decryption process, since it was probably never intended for the server to have access to the decryption keys. Additionally, if the server does have access to the keys to perform the decryption, there is probably a nice way to do this with php code. (I'm not a php dev, so I can't speak to exactly what php code you would need to write the decryption php script).

总的来说,用例让我感到困惑。我猜测最初设计为在浏览器中进行客户端解密的应用程序之所以这样做是因为服务器没有执行解密的密钥。因此,如果这是其他人编写的应用程序并且您正在尝试对其进行更改,则您需要确保您确实拥有服务器端执行解密过程所需的密钥,因为它可能从未打算用于服务器访问解密密钥。此外,如果服务器确实可以访问密钥来执行解密,那么使用 php 代码可能有一个很好的方法来做到这一点。(我不是 php 开发人员,所以我无法确切地说出编写解密 php 脚本所需的 php 代码)。

Hope this helps. Mark

希望这可以帮助。标记

回答by SubniC

It looks well if you are not using AJAX (if you are may be you need to eval() your response)

如果您不使用 AJAX,它看起来不错(如果您可能需要 eval() 您的响应)

I have tried a shorted version of your code and it is working fine.

我已经尝试了你的代码的一个简短版本,它工作正常。

<!doctype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>AES (Rijndael) Encryption Test in JavaScript</title>
<script src="aes-enc.js" type="text/javascript" language="JavaScript"></script>
<script src="aes-dec.js" type="text/javascript" language="JavaScript"></script>
<script src="aes-test.js" type="text/javascript" language="JavaScript"></script>
<script type="text/javascript">

function doDecryption()
{
    document.write("Inside Javascript");
}

</script>
</head>

<body>
<?php
    echo '<script type="text/javascript">
    doDecryption();
    </script>';
    echo "whats happening";
?>
</body>
</html>

And the result is

结果是

Inside Javascriptwhats happening

HTH, Regards.

HTH,问候。