繁体   English   中英

从 JavaScript 拨打 php function

[英]Call php function from JavaScript

有没有办法可以通过 JS function 运行 php function?

是这样的:

<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php 
query("hello");       ?>";    
}
</script>

<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"     
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>

我基本上想运行 php function query("hello") ,当我点击名为“测试”的 href 时,它会调用 php function。

本质上,这就是AJAX用途 您的页面加载,并且您将事件添加到元素。 当用户触发事件时,比如通过单击某物,您的 Javascript 使用XMLHttpRequest 对象向服务器发送请求。

在服务器响应(可能是输出)之后,另一个 Javascript 函数/事件为您提供了使用该输出的位置,包括像任何其他 HTML 一样简单地将其粘贴到页面中。

您可以使用纯 Javascript “手动”完成,也可以使用 jQuery。 根据您的项目大小和特定情况,使用纯 Javascript 可能更简单。

纯Javascript

在这个非常基本的示例中,当用户单击链接时,我们向myAjax.php发送请求。 服务器将生成一些内容,在本例中为“hello world!”。 我们将放入带有 id output的 HTML 元素。

javascript

// handles the click event for link 1, sends the query
function getOutput() {
  getRequest(
      'myAjax.php', // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}  
// handles drawing an error message
function drawError() {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? 
                success(req.responseText) : error(req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

的HTML

<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>

PHP的

// file myAjax.php
<?php
  echo 'hello world!';
?>

试试看:http: //jsfiddle.net/GRMule/m8CTk/


使用 javascript 库(jQuery 等)

可以说,这是很多 Javascript 代码。 当然,您可以通过收紧块或使用更简洁的逻辑运算符来缩短它,但仍有很多事情要做。 如果您打算在您的项目中做很多此类事情,那么最好使用 javascript 库。

使用与上面相同的 HTML 和 PHP,这是您的整个脚本(页面中包含 jQuery)。 我已经稍微收紧了代码以更符合 jQuery 的一般风格,但你明白了:

// handles the click event, sends the query
function getOutput() {
   $.ajax({
      url:'myAjax.php',
      complete: function (response) {
          $('#output').html(response.responseText);
      },
      error: function () {
          $('#output').html('Bummer: there was an error!');
      }
  });
  return false;
}

试试看:http: //jsfiddle.net/GRMule/WQXXT/

不要急于使用 jQuery:添加任何库仍然会向您的项目添加数百或数千行代码,就像您已经编写它们一样肯定。 在 jQuery 库文件中,您会发现与第一个示例类似的代码,以及更多. 这可能是件好事,也可能不是。 计划并考虑您项目的当前规模和未来扩展的可能性以及目标环境或平台。

如果这就是您需要做的所有事情,请编写一次纯 JavaScript,然后您就完成了。

文档

PHP 在服务器上进行评估; javascript 在客户端/浏览器上进行评估,因此您不能直接从 javascript 调用 PHP 函数。 但是您可以使用 AJAX 向将激活 PHP 功能的服务器发出 HTTP 请求。

从 JS 执行 PHP 的唯一方法是 AJAX。 您可以将数据发送到服务器(例如,GET /ajax.php?do=someFunction),然后在 ajax.php 中编写:

function someFunction() {
    echo 'Answer';
}

if ($_GET['do'] === "someFunction") {
    someFunction();
}

然后,用 JS 捕捉答案(我使用 jQuery 来发出 AJAX 请求)

可能您需要某种格式的答案。 请参阅 JSON 或 XML,但 JSON 很容易与 JavaScript 一起使用。 在 PHP 中,您可以使用函数 json_encode($array); 它将数组作为参数。

我最近发布了一个 jQuery 插件,它允许您以各种方式进行 PHP 函数调用: https ://github.com/Xaxis/jquery.php

简单示例用法:

// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

我有一种方法可以对页面上编写的 PHP 函数进行 Javascript 调用(客户端脚本)。 “待执行”的 PHP 部分仅在加载或刷新时发生在服务器端。 您避免了“一些”服务器端资源。 因此,操作 DOM:

<?PHP

echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";

function myPhp(){
echo"The page says: Hello world!<br>";

echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";
}
?>

<div id="mainx"></div>

<script>
function callPhp(){
var tagDiv1 = document.createElement("div");
tagDiv1.id = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";
document.getElementById("mainx").appendChild(tagDiv1);
}
</script>

<input type="button" value="CallPHP" onclick="callPhp()">

注意:texto.txt 文件的内容为“Hello world! (旧内容)。

“事实”是,每当我单击“CallPhp”按钮时,我都会收到消息“Hello world!” 印在我的页面上。 因此,通过 Javascript 执行 PHP 函数并不总是需要服务器端脚本。

但是 bash 命令的执行只发生在页面加载或刷新时,而不是因为之前引发的那种 Javascript 明显调用。 加载页面后,执行 bash 脚本需要对服务器端 PHP 资源进行真正的调用(PHP、Ajax)。

因此,如果您不希望用户知道服务器上正在运行哪些命令:

  • 您“应该”通过服务器端的 PHP 脚本(PHP 表单或客户端的 Ajax)间接使用命令的执行。

否则:

  • 如果服务器端的命令输出没有延迟:
    • 您“可以”直接从页面执行命令(更少的“认知”资源——更少的 PHP 和更多的 Bash——以及更少的代码、更少的时间,如果你了解 bash 语言,通常更容易、更舒服)。
  • 否则:
    • 您“必须”使用 Ajax。

暂无
暂无

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

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