如何在单击按钮时调用 php 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5403736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to call a php function on button click
提问by Gnanendra
These are two files
这是两个文件
Calling.php
调用.php
<html>
<body>
<form action="Called.php" method="get">
<input type="button" name="B1" value="B1">
<input type="button" name="B2" value="B2">
<input type="Submit" name="Submit1"/>
<!-- <a href="http://www.google.com?act=google">Google</a>
<a href="http://www.yahoo.com?act=yahoo">yahoo</a>
-->
</form>
</body>
</html>
And Called.php
并称为.php
<?php
if(isset($_GET("Submit1")))
{
echo("<script>location.href = 'http://stackoverflow.com';</script>");
}
if(isset($_GET["B1"]))
{
echo("<script>location.href = 'http://google.com/';</script>");
exit();
}
if(isset($_GET["B2"]))
- List item
{
echo "<meta http-equiv='refresh' content='0;url=http://www.yahoo.com'>";
exit();
}
?>
When i click the buttons "B1" and "B2", page will blink but now where redirect and third one "Submit" button will redirect to new page and there i am getting the out put as "Called.php".
当我点击按钮“B1”和“B2”时,页面会闪烁,但现在重定向和第三个“提交”按钮将重定向到新页面,我得到的输出为“Called.php”。
Please spend few seconds for this php beginner.
请为这个php初学者花几秒钟。
回答by GordonM
You can't directly because the button click is a client side activity and PHP is server side. If you make all the inputs submit then the one the user clicked will be submitted as part of the $_GET array but that only works if the user clicks one of them and doesn't submit the form by, say, hitting Enter in a text input.
您不能直接,因为按钮单击是客户端活动,而 PHP 是服务器端。如果您提交所有输入,则用户单击的输入将作为 $_GET 数组的一部分提交,但仅当用户单击其中一个输入且不提交表单时才有效,例如在文本中按 Enter输入。
You could attach AJAX events to the button and have them trigger off a PHP script to run the function you want to run, but that has its own set of issues.
您可以将 AJAX 事件附加到按钮,并让它们触发 PHP 脚本以运行您想要运行的函数,但这有其自身的一系列问题。
EDIT: I should note that your method of redirecting is rather inelegant to say the least. You can just use header() to do the redirection, it would be much cleaner than all this messing around with echoing out javascript.
编辑:我应该注意到,您的重定向方法至少可以说是相当不雅的。您可以只使用 header() 来进行重定向,它会比所有这些与回显 javascript 混在一起的东西要干净得多。
回答by Shameer
You need to use Ajax to do this. If you are using jQuery ajax the code will look something like this
您需要使用 Ajax 来执行此操作。如果您使用 jQuery ajax,代码将如下所示
$(function(){
$('input[type="button"]').click(function(){
var name = $(this).attr('value');
$.ajax({
type :'GET',
url : 'Calling.php',
data :{name:name}
success : function(data) {
//do smthng
}
})
})
})
//Code is not tested. Need to verify.
//代码未测试。需要验证。