这是我要运行的代码...计算是在PHP中,我希望它在按钮标记的onclick事件上运行。
<button onclick = "myFunction()"> Click here to calculate</button>
<script>
function myFunction()
{ <?php $x = 100; $y = 2;
echo "This is multiplication of x and y ="." ". $x*$y."</br>";
echo "This is addition of x and y ="." ".($x + $y)."</br>";
echo "This is subtraction of x and y ="." ".($x - $y)."</br>";
echo "This is division of x and y = "." " .$x/$y."</br>";
echo "This is remainder of x and y ="." ". $x % $y."</br>"; ?>
}
myFunction();
</script>
这可能吗?
请帮帮我..
答案 0 :(得分:2)
你的问题有些混乱。
PHP是服务器端脚本语言,因此在浏览器上呈现页面之前执行它。
这意味着您的功能在服务器中执行,而不是在用户点击时执行。
如果你想在点击时执行一些计算,你应该使用javascript,因为它是浏览器可以理解的语言。
如果要使用PHP计算值,则应使用AJAX。要做到这一点,您可以使用jquery方法,如$.ajax()
,$.get()
或$.post()
答案 1 :(得分:2)
在您寻求帮助时,请查看:
1: - 创建一个HTML文件
<html>
<script src = "jquery-1.9.1.js"></script>
<button id ="click_button"> Click here to calculate</button>
<script>
$(document).ready(function(){
$('#click_button').click(function(){
$.ajax({
url:'buttonclick.php',
success: function(Response){
alert(Response);
}
});
});
});
</script>
</html>
2: - 创建一个PHP文件(名称为buttonclick.php): -
<?php
function myFunction()
{
$x = 100; $y = 2;
echo "This is multiplication of x and y ="." ". $x*$y."</br>";
echo "This is addition of x and y ="." ".($x + $y)."</br>";
echo "This is subtraction of x and y ="." ".($x - $y)."</br>";
echo "This is division of x and y = "." " .$x/$y."</br>";
echo "This is remainder of x and y ="." ". $x % $y."</br>";
}
return myFunction();
?>
输出: - http://prntscr.com/6l56dq
注意: - 文件(html和php)和jquery文件(jquery-1.9.1.js)都在同一工作目录中。此外,它取决于您如何显示响应。我只是给你一个容易理解的例子。