在 html 按钮上运行 PHP 函数单击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15957862/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:15:26  来源:igfitidea点击:

Run PHP function on html button click

javascriptphphtmlajaxbutton

提问by Mihai Bujanca

I need to run some PHP function when a button is clicked. I know this is not supposed to be php's use, rather js should do it, but what my functions are doing in gathering data from a server when the user asks it. Specifically, it gets some user data and writes it to a file, and the user should decide what data will be gathered.
How can I do this? I saw the post Run PHP File On Button Clickbut I am still not sure how to use it.
I'm learning, so please don't be too harsh

单击按钮时,我需要运行一些 PHP 函数。我知道这不应该是 php 的用途,而是 js 应该这样做,但是当用户询问时,我的函数在从服务器收集数据时正在做什么。具体来说,它获取一些用户数据并将其写入文件,由用户决定将收集哪些数据。
我怎样才能做到这一点?我看到了在按钮单击上运行 PHP 文件的帖子,但我仍然不确定如何使用它。
我正在学习,所以请不要太苛刻

I have tried onclick()and all sorts of things but it didn't lead to anything useful

我已经尝试过onclick()各种各样的事情,但没有产生任何有用的东西

回答by Menios

A php file is run whenever you access it via an HTTP request be it GET,POST, PUT.

每当您通过 HTTP 请求(GET、POST、PUT)访问它时,都会运行一个 php 文件。

You can use JQuery/Ajax to send a request on a button click, or even just change the URL of the browser to navigate to the php address.

您可以使用 JQuery/Ajax 在单击按钮时发送请求,甚至只需更改浏览器的 URL 以导航到 php 地址。

Depending on the data sent in the POST/GET you can have a switch statement running a different function.

根据 POST/GET 中发送的数据,您可以让 switch 语句运行不同的函数。

Specifying Function via GET

通过 GET 指定函数

You can utilize the code here: How to call PHP function from string stored in a Variablealong with a switch statement to automatically call the appropriate function depending on data sent.

您可以使用此处的代码:如何从存储在变量中的字符串以及 switch 语句调用 PHP 函数,以根据发送的数据自动调用适当的函数。

So on PHP side you can have something like this:

所以在 PHP 方面,你可以有这样的东西:

<?php

//see http://php.net/manual/en/function.call-user-func-array.php how to use extensively
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";

function test()
{
echo("test");
}

function hello()
{
echo("hello");
}

?>

and you can make the simplest get request using the address bar as testing:

您可以使用地址栏进行最简单的获取请求作为测试:

http://127.0.0.1/test.php?runFunction=hellodddddd

results in:

结果是:

Function not found or wrong input

http://127.0.0.1/test.php?runFunction=hello

results in:

结果是:

hello

Sending the Data

发送数据

GET Request via JQuery

通过 JQuery 获取请求

See: http://api.jquery.com/jQuery.get/

见:http: //api.jquery.com/jQuery.get/

$.get("test.cgi", { name: "John"})
.done(function(data) {
  alert("Data Loaded: " + data);
});

POST Request via JQuery

通过 JQuery POST 请求

See: http://api.jquery.com/jQuery.post/

见:http: //api.jquery.com/jQuery.post/

$.post("test.php", { name: "John"} );

GET Request via Javascript location

通过 Javascript 位置的 GET 请求

See: http://www.javascripter.net/faq/buttonli.htm

请参阅:http: //www.javascripter.net/faq/buttonli.htm

<input type=button 
value="insert button text here"
onClick="self.location='Your_URL_here.php?name=hello'">

Reading the Data (PHP)

读取数据 (PHP)

See PHP Turotial for reading post and get: http://www.tizag.com/phpT/postget.php

请参阅 PHP Turotial 以阅读帖子并获取:http://www.tizag.com/phpT/postget.php

Useful Links

有用的链接

http://php.net/manual/en/function.call-user-func.phphttp://php.net/manual/en/function.function-exists.php

http://php.net/manual/en/function.call-user-func.php http://php.net/manual/en/function.function-exists.php

回答by bksi

If you want to make a server request you should use AJAX, so you can send your desired parameters to the server and it can run whatever php you want with these parameters.

如果你想发出一个服务器请求,你应该使用 AJAX,这样你就可以将你想要的参数发送到服务器,它可以使用这些参数运行你想要的任何 php。

Example with pure javascript:

纯 javascript 示例:

<input type="text" id="name" value="..."/>
<input type="text" id="location" value="..."/>
<input type="button" onclick="ajaxFunction();" value="Submit" />
<div id="ajaxDiv"></div>
<script type="text/javascript">    
    function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                var ajaxDisplay = document.getElementById('ajaxDiv');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
            }
        }
        var name = document.getElementById('name').value;
        var location = document.getElementById('location').value;
        var queryString = "?name=" + name + "&location=" + location;
        ajaxRequest.open("POST", "some.php" + queryString, true);
        ajaxRequest.send(null); 
    }
</script>

Example with jQuery Ajax:http://api.jquery.com/jQuery.ajax/

jQuery Ajax 示例:http : //api.jquery.com/jQuery.ajax/

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

You can have one file with functions called for example functions.php

您可以拥有一个包含函数的文件,例如 functions.php

functions.php

函数.php

<?php
  myFunction($Name, $Location) {
      // etc...
  }
  myFunction2() {
  }
  // ... many functions
?>

some.php

一些.php

<?php include("functions.php");    
$Name = $_POST['name'];
$Location = $_POST['location'];

myFunction($Name, $Location);

// make what you want with these variables...?>

回答by GriffLab

Use ajax, a simple example,

使用ajax,一个简单的例子,

HTML

HTML

<button id="button">Get Data</button>

Javascript

Javascript

var button = document.getElementById("button");

button.addEventListener("click" ajaxFunction, false);

var ajaxFunction = function () {
    // ajax code here
}

Alternatively look into jquery ajaxhttp://api.jquery.com/jQuery.ajax/

或者查看jquery ajaxhttp://api.jquery.com/jQuery.ajax/

回答by Uday Hiwarale

<?php
if (isset($_POST['str'])){
function printme($str){
echo $str;
}

printme("{$_POST['str']}");
}
?>
<form action="<?php $_PHP_SELF ?>" method="POST">
<input type="text" name="str" /> <input type="submit" value="Submit"/>
</form>

回答by piry

Use an AJAX Request on your PHP file, then display the result on your page, without any reloading.

对 PHP 文件使用 AJAX 请求,然后在页面上显示结果,无需重新加载。

http://api.jquery.com/load/This is a simple solution if you don't need any POST data.

http://api.jquery.com/load/如果您不需要任何 POST 数据,这是一个简单的解决方案。

回答by Virus721

It depends on what function you want to run. If you need something done on server side, like querying a database or setting something in the session or anything that can not be done on client side, you need AJAX, else you can do it on client-side with JavaScript. Don't make the server work when you can do what you need to do on client side.

这取决于您要运行的功能。如果你需要在服务器端做一些事情,比如查询数据库或在会话中设置一些东西或者任何不能在客户端完成的事情,你需要 AJAX,否则你可以在客户端使用 JavaScript 来完成。当你可以在客户端做你需要做的事情时,不要让服务器工作。

jQuery provides an easy way to do ajax : http://api.jquery.com/jQuery.ajax/

jQuery 提供了一种简单的 ajax 方法:http: //api.jquery.com/jQuery.ajax/