javascript-单击按钮即可调用php函数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-单击按钮即可调用php函数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2151字,纯文字阅读大概需要4分钟。
内容图文
![javascript-单击按钮即可调用php函数](/upload/InfoBanner/zyjiaocheng/661/c212a7e8905b4641934eb61e1f27a517.jpg)
我试图使用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调用来做到这一点,在该调用中,您将在按钮的onclick上调用客户端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>
内容总结
以上是互联网集市为您收集整理的javascript-单击按钮即可调用php函数全部内容,希望文章能够帮你解决javascript-单击按钮即可调用php函数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。