【问题标题】:Call php function on click of a button单击按钮调用php函数
【发布时间】:2014-11-01 06:11:00
【问题描述】:

我正在尝试使用 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>

【问题讨论】:

标签: javascript php jquery


【解决方案1】:

您不能像上面解释的那样调用 php 函数。因为 php 脚本执行发生在网页源从服务器发送到客户端浏览器之前。

但是,您可以通过 ajax 调用来实现,在该调用中,您在单击按钮时调用客户端 js 函数,然后该函数对服务器端页面进行 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> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2014-01-11
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多