簡體   English   中英

單擊按鈕調用php函數

[英]Call php function on click of a button

我試圖通過使用Javascript點擊按鈕來調用php函數。 它似乎沒有正常工作。

有沒有更好的方法來點擊按鈕調用PHP功能

<!DOCTYPE html>
<html>

<head>
<script type="text/javascript">
function executeShellScript(clicked)
{
    var x="<?php ex(); ?>";
    alert(x);
    return false;
}
</script>
</head>

<body>


<input type="button" id="sample" value="click" onclick="executeShellScript()"/>

<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

function ex(){

echo "Trying to run shell script from the web browser";
echo "<br>";

$contents = file_get_contents('/var/www/shellscriptphp/helloworld.sh');
echo shell_exec($contents);

$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
echo $result;
}

?>

</body>
</html>

你不能像上面解釋的那樣調用php函數。 因為php腳本執行發生在網頁源從服務器發送到客戶端瀏覽器之前。

但是你可以通過一個ajax調用來實現它,你可以在其中調用一個客戶端js函數onclick按鈕,並且該函數inturn對服務器端頁面進行ajax調用並返回結果。

例:

以下是您可以參考的示例代碼。 此頁面向自己發出POST ajax請求並獲取響應。 讓我知道錯誤,因為我沒有在這里運行它。

<?php
/** this code handles the post ajax request**/
if(isset($_POST['getAjax'])) {

    /* you can do this below settings via your php ini also. no relation with our stuff */
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);

    /* setting content type as json */
    header('Content-Type: application/json');
    $result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');       
    /* making json string with the result from shell script */
    echo json_encode(array("result"=>$result));
    /* and we are done and exit */
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
function executeShellScript(clicked)
{
    //$_SERVER["REQUEST_URI"] is used to refer to the current page as we have the ajax target as this same page
    $.post('<?PHP echo $_SERVER["REQUEST_URI"]; ?>',{"getAjax":true}, function(data) {
        alert(data['result']);
        return false;
    });


}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
</body>
</html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM