如何从PHP调用JavaScript函数?

<?php

  jsfunction();
  // or
  echo(jsfunction());
  // or
  // Anything else?

下面的代码来自xyz.html(单击按钮),它调用外部xyz.js中的wait()。这个wait()调用wait.php。

function wait() 
{
  xmlhttp=GetXmlHttpObject();
  var url="wait.php"; \
  xmlhttp.onreadystatechange=statechanged; 
  xmlhttp.open("GET", url, true); 
  xmlhttp.send(null);
} 

function statechanged()
{ 
  if(xmlhttp.readyState==4) {
       document.getElementById("txt").innerHTML=xmlhttp.responseText;
  }
}

和wait.php

<?php echo "<script> loadxml(); </script>"; 

其中loadxml()以同样的方式从另一个PHP文件调用代码。

除此之外,loadxml()工作得很好,但它没有以我想要的方式调用。


当前回答

像这样试试

<?php
 if(your condition){
     echo "<script> window.onload = function() {
     yourJavascriptFunction(param1, param2);
 }; </script>";
?>

其他回答

PHP在服务器中运行。JavaScript在客户端中运行。php不能调用JavaScript函数。

你不能。你可以从PHP输出的HTML中调用JS函数,但这完全是另一回事。

我不接受反对者的答案。

如果你发现了一些特殊的软件包可以让它工作,那么你可以自己做!所以,我不相信这些答案。

onClick是一个涉及最终用户的拼凑,因此是不可接受的。

@umesh很接近,但它不是一个独立的程序。以下是这样的(摘自他的回答):

<script type="text/javascript">
function JSFunction() {
    alert('In test Function');  // This demonstrates that the function was called
}
</script>

<?php
// Call a JS function "from" php

if (true) {   // This if() is to point out that you might
              // want to call JSFunction conditionally
    // An echo like this is how you implant the 'call' in a way
    // that it will be invoked in the client.
    echo '<script type="text/javascript">
         JSFunction();
    </script>';
}

函数在使用之前声明是很重要的。(我不知道“以前”是指“词汇上的以前”还是“时间上的以前”;在上面的示例代码中,两者都是。)

像这样试试

<?php
 if(your condition){
     echo "<script> window.onload = function() {
     yourJavascriptFunction(param1, param2);
 }; </script>";
?>

如果你想回显它以便以后执行,这是可以的

如果你想执行JS并在PHP中使用结果,请使用V8JS

V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');

如需进一步参考,请参考: php v8js中的扩展是什么?

如果你想要执行HTML&JS并在PHP中使用输出http://htmlunit.sourceforge.net/是你的解决方案