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