简体   繁体   English

从 JavaScript 拨打 php function

[英]Call php function from JavaScript

Is there a way I can run a php function through a JS function?有没有办法可以通过 JS function 运行 php function?

something like this:是这样的:

<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>

I basically want to run the php function query("hello") , when I click on the href called "Test" which would call the php function.我基本上想运行 php function query("hello") ,当我点击名为“测试”的 href 时,它会调用 php function。

This is, in essence, what AJAX is for .本质上,这就是AJAX用途 Your page loads, and you add an event to an element.您的页面加载,并且您将事件添加到元素。 When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.当用户触发事件时,比如通过单击某物,您的 Javascript 使用XMLHttpRequest 对象向服务器发送请求。

After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.在服务器响应(可能是输出)之后,另一个 Javascript 函数/事件为您提供了使用该输出的位置,包括像任何其他 HTML 一样简单地将其粘贴到页面中。

You can do it "by hand" with plain Javascript , or you can use jQuery.您可以使用纯 Javascript “手动”完成,也可以使用 jQuery。 Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .根据您的项目大小和特定情况,使用纯 Javascript 可能更简单。

Plain Javascript纯Javascript

In this very basic example, we send a request to myAjax.php when the user clicks a link.在这个非常基本的示例中,当用户单击链接时,我们向myAjax.php发送请求。 The server will generate some content, in this case "hello world!".服务器将生成一些内容,在本例中为“hello world!”。 We will put into the HTML element with the id output .我们将放入带有 id output的 HTML 元素。

The javascript 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;
}

The HTML的HTML

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

The PHP PHP的

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

Try it out: http://jsfiddle.net/GRMule/m8CTk/试试看:http: //jsfiddle.net/GRMule/m8CTk/


With a javascript library (jQuery et al)使用 javascript 库(jQuery 等)

Arguably, that is a lot of Javascript code.可以说,这是很多 Javascript 代码。 You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there.当然,您可以通过收紧块或使用更简洁的逻辑运算符来缩短它,但仍有很多事情要做。 If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.如果您打算在您的项目中做很多此类事情,那么最好使用 javascript 库。

Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page).使用与上面相同的 HTML 和 PHP,这是您的整个脚本(页面中包含 jQuery)。 I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:我已经稍微收紧了代码以更符合 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;
}

Try it out: http://jsfiddle.net/GRMule/WQXXT/试试看:http: //jsfiddle.net/GRMule/WQXXT/

Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them.不要急于使用 jQuery:添加任何库仍然会向您的项目添加数百或数千行代码,就像您已经编写它们一样肯定。 Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more .在 jQuery 库文件中,您会发现与第一个示例类似的代码,以及更多. That may be a good thing, it may not.这可能是件好事,也可能不是。 Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.计划并考虑您项目的当前规模和未来扩展的可能性以及目标环境或平台。

If this is all you need to do, write the plain javascript once and you're done.如果这就是您需要做的所有事情,请编写一次纯 JavaScript,然后您就完成了。

Documentation文档

PHP is evaluated at the server; PHP 在服务器上进行评估; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly . javascript 在客户端/浏览器上进行评估,因此您不能直接从 javascript 调用 PHP 函数。 But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.但是您可以使用 AJAX 向将激活 PHP 功能的服务器发出 HTTP 请求。

The only way to execute PHP from JS is AJAX.从 JS 执行 PHP 的唯一方法是 AJAX。 You can send data to server (for eg, GET /ajax.php?do=someFunction) then in ajax.php you write:您可以将数据发送到服务器(例如,GET /ajax.php?do=someFunction),然后在 ajax.php 中编写:

function someFunction() {
    echo 'Answer';
}

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

and then, catch the answer with JS (i'm using jQuery for making AJAX requests)然后,用 JS 捕捉答案(我使用 jQuery 来发出 AJAX 请求)

Probably you'll need some format of answer.可能您需要某种格式的答案。 See JSON or XML, but JSON is easy to use with JavaScript.请参阅 JSON 或 XML,但 JSON 很容易与 JavaScript 一起使用。 In PHP you can use function json_encode($array);在 PHP 中,您可以使用函数 json_encode($array); which gets array as argument.它将数组作为参数。

I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php我最近发布了一个 jQuery 插件,它允许您以各种方式进行 PHP 函数调用: https ://github.com/Xaxis/jquery.php

Simple example usage:简单示例用法:

// 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/"]

I have a way to make a Javascript call to a PHP function written on the page (client-side script).我有一种方法可以对页面上编写的 PHP 函数进行 Javascript 调用(客户端脚本)。 The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. “待执行”的 PHP 部分仅在加载或刷新时发生在服务器端。 You avoid 'some' server-side resources.您避免了“一些”服务器端资源。 So, manipulating the DOM:因此,操作 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()">

Note: The texto.txt file has the content 'Hello world!注意:texto.txt 文件的内容为“Hello world! (Old content). (旧内容)。

The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' “事实”是,每当我单击“CallPhp”按钮时,我都会收到消息“Hello world!” printed on my page.印在我的页面上。 Therefore, a server-side script is not always required to execute a PHP function via Javascript.因此,通过 Javascript 执行 PHP 函数并不总是需要服务器端脚本。

But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before.但是 bash 命令的执行只发生在页面加载或刷新时,而不是因为之前引发的那种 Javascript 明显调用。 Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.加载页面后,执行 bash 脚本需要对服务器端 PHP 资源进行真正的调用(PHP、Ajax)。

So, If you don't want the user to know what commands are running on the server:因此,如果您不希望用户知道服务器上正在运行哪些命令:

  • You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).您“应该”通过服务器端的 PHP 脚本(PHP 表单或客户端的 Ajax)间接使用命令的执行。

Otherwise:否则:

  • If the output of commands on the server-side is not delayed:如果服务器端的命令输出没有延迟:
    • You 'can' use the execution of the commands directly from the page (less 'cognitive' resources—less PHP and more Bash—and less code, less time, usually easier, and more comfortable if you know the bash language).您“可以”直接从页面执行命令(更少的“认知”资源——更少的 PHP 和更多的 Bash——以及更少的代码、更少的时间,如果你了解 bash 语言,通常更容易、更舒服)。
  • Otherwise:否则:
    • You 'must' use Ajax.您“必须”使用 Ajax。

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

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