Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

how to call a php function on button click

These are two files

Calling.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
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".

Please spend few seconds for this php beginner.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...