简体   繁体   English

如何从 PHP 调用 JavaScript function?

[英]How to call a JavaScript function from PHP?

How to call a JavaScript function from PHP?如何从 PHP 调用 JavaScript function?

<?php

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

The following code is from xyz.html (on a button click) it calls a wait() in an external xyz.js .以下代码来自xyz.html (单击按钮)它在外部xyz.js中调用wait() This wait() calls wait.php.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;
  }
}

and wait.php等待。php

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

where loadxml() calls code from another PHP file the same way.其中loadxml()以相同的方式从另一个 PHP 文件调用代码。

The loadxml() is working fine otherwise, but it is not being called the way I want it.否则loadxml()工作正常,但没有按我想要的方式调用它。

As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.就 PHP 而言(或者实际上是一般的 Web 服务器),HTML 页面并不比一个大字符串复杂。

All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.您可以使用 PHP 之类的语言完成的所有奇特工作——从数据库和 Web 服务中读取等等——最终的最终目标是完全相同的基本原则:生成一串 HTML*。

Your big HTML string doesn't become anything more special than that until it's loaded by a web browser.在 Web 浏览器加载之前,您的大 HTML 字符串不会变得比这更特别。 Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.一旦浏览器加载页面,所有其他的魔法发生-布局,盒模型的东西,DOM生成,并且很多其他的东西,包括JavaScript执行。

So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".因此,您不是“从 PHP 调用 JavaScript”,而是“在输出中包含 JavaScript 函数调用”。

There are many ways to do this, but here are a couple.有很多方法可以做到这一点,但这里有几个。

Using just PHP:仅使用 PHP:

echo '<script type="text/javascript">',
     'jsfunction();',
     '</script>'
;

Escaping from php mode to direct output mode:从php模式转为直接输出模式:

<?php
    // some php stuff
?>
<script type="text/javascript">
    jsFunction();
</script>

You don't need to return a function name or anything like that.您不需要返回函数名称或类似的东西。 First of all, stop writing AJAX requests by hand.首先,停止手动编写 AJAX 请求。 You're only making it hard on yourself.你只是让自己很难受。 Get jQuery or one of the other excellent frameworks out there.获取 jQuery 或其他优秀框架之一。

Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.其次,了解一旦收到来自 AJAX 调用的响应,您就已经将要执行 javascript 代码。

Here's an example of what I think you're doing with jQuery's AJAX这是我认为您正在使用 jQuery 的 AJAX 执行的操作的示例

$.get(
    'wait.php',
    {},
    function(returnedData) {
        document.getElementById("txt").innerHTML = returnedData;

        //  Ok, here's where you can call another function
        someOtherFunctionYouWantToCall();

        // But unless you really need to, you don't have to
        // We're already in the middle of a function execution
        // right here, so you might as well put your code here
    },
    'text'
);

function someOtherFunctionYouWantToCall() {
    // stuff
}

Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.现在,如果您对将函数名称从 PHP 发送回 AJAX 调用一事无动于衷,您也可以这样做。

$.get(
    'wait.php',
    {},
    function(returnedData) {
        // Assumes returnedData has a javascript function name
        window[returnedData]();
    },
    'text'
);

* Or JSON or XML etc. * 或 JSON 或 XML 等。

I always just use echo "<script> function(); </script>";我总是只使用echo "<script> function(); </script>"; or something similar.或类似的东西。 You're not technically calling the function in PHP, but this is as close as you're going to get.从技术上讲,您不是在 PHP 中调用该函数,但这与您将要获得的非常接近。

Per now (February 2012) there's a new feature for this.现在(2012 年 2 月)有一个新功能。 Check here在这里查看

Code sample (taken from the web):代码示例(摘自网络):

<?php

$v8 = new V8Js();

/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;

try {
  var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
  var_dump($e);
}

?>

You can't.你不能。 You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.您可以从 PHP输出的 HTML 中调用 JS 函数,但这完全是另一回事。

If you want to echo it out for later execution it's ok如果您想将其回显以供以后执行,则可以

If you want to execute the JS and use the results in PHP use V8JS如果要执行 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"); }');

You can refer here for further reference: What are Extensions in php v8js?你可以参考这里进一步参考: What are Extensions in php v8js?

If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution如果您想执行 HTML&JS 并使用 PHP 中的输出http://htmlunit.sourceforge.net/是您的解决方案

Thats not possible.那是不可能的。 PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. PHP 是一种服务器端语言和 JavaScript 客户端,他们对彼此的了解并不多。 You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer).你需要一个服务器端的 JavaScript 解释器(比如 Aptanas Jaxer)。 Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).也许您真正想要做的是使用类似架构的 Ajax(JavaScript 函数异步调用 PHP 脚本并对结果执行某些操作)。

<td onClick= loadxml()><i>Click for Details</i></td>

function loadxml()
{
    result = loadScriptWithAjax("/script.php?event=button_clicked");
    alert(result);
}

// script.php
<?php
    if($_GET['event'] == 'button_clicked')
        echo "\"You clicked a button\"";
?>

try like this像这样尝试

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

you can try this one also:-你也可以试试这个:-

    public function PHPFunction()
    {
            echo '<script type="text/javascript">
                 test();
            </script>'; 
    }
    <script type="text/javascript">
    public function test()
    {
        alert('In test Function');
    }
    </script>

PHP runs in the server. PHP 在服务器中运行。 JavaScript runs in the client. JavaScript 在客户端运行。 So php can't call a JavaScript function.所以 php 不能调用 JavaScript 函数。

You may not be able to directly do this, but the Xajax library is pretty close to what you want.您可能无法直接执行此操作,但Xajax库非常接近您想要的。 I will demonstrate with an example.我将用一个例子来演示。 Here's a button on a webpage:这是网页上的一个按钮:

<button onclick="xajax_addCity();">Add New City</button> 

Our intuitive guess would be that xajax_addCity() is a Javascript function, right?我们的直觉猜测是xajax_addCity()是一个 Javascript 函数,对吧? Well, right and wrong.嗯,对与错。 The cool thing Xajax allows is that we don't have any JS function called xajax_addCity() , but what we do have is a PHP function called addCity() that can do whatever PHP does! Xajax 允许的很酷的事情是我们没有任何名为xajax_addCity() JS 函数,但我们拥有的是一个名为addCity()的 PHP 函数,它可以做任何 PHP 做的事!

<?php function addCity() { echo "Wow!"; } ?>

Think about it for a minute.想一想。 We are virtually invoking a PHP function from Javascript code!我们实际上是从 Javascript 代码调用 PHP 函数! That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!那个过于简化的例子只是为了激发食欲,在 Xajax 站点上有更好的解释,玩得开心!

I don't accept the naysayers' answers.我不接受反对者的回答。

If you find some special package that makes it work, then you can do it yourself !如果你找到一些特殊的包让它工作,那么你可以自己做 So, I don't buy those answers.所以,我不买那些答案。

onClick is a kludge that involves the end-user, hence not acceptable. onClick是一个涉及最终用户的杂项,因此是不可接受的。

@umesh came close, but it was not a standalone program. @umesh 很接近,但它不是一个独立的程序。 Here is such (adapted from his Answer):这是这样的(改编自他的回答):

<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>';
}

if you want to call method inside echo you have to enclose them into single quotes: 如果要在echo中调用method,则必须将它们用单引号引起来:

    function f() {
      //code
      alert("its calling from echo ");
    }

    echo "<td onclick='f();'>".Method calling."</td>";

For some backend node processing, you can run JS script via shell and return the result to PHP via console.log对于一些后端节点处理,可以通过shell运行JS脚本,通过console.log返回结果给PHP

  function executeNode($script)
  {
    return shell_exec('node -e \'eval(Buffer.from("'.base64_encode($script).'", "base64").toString())\'');
  }


  $jsCode = 'var a=1; var b=2; console.log(a+b);';
  
  echo executeNode($jsCode);

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

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