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

Mih*_*nca 10 html javascript php html5 button

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

我尝试onclick()了各种各样的东西,但它没有带来任何有用的东西

Men*_*los 13

每当您通过HTTP请求访问它时都会运行php文件,无论是GET,POST,PUT.

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

根据POST/GET中发送的数据,您可以使用运行不同功能的switch语句.

通过GET指定功能

您可以在此处使用以下代码:如何从存储在Variable中的字符串调用PHP函数以及switch语句,以根据发送的数据自动调用相应的函数.

所以在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");
}

?>
Run Code Online (Sandbox Code Playgroud)

并且您可以使用地址栏作为测试来发出最简单的get请求:

http://127.0.0.1/test.php?runFunction=hellodddddd
Run Code Online (Sandbox Code Playgroud)

结果是:

Function not found or wrong input

http://127.0.0.1/test.php?runFunction=hello
Run Code Online (Sandbox Code Playgroud)

结果是:

hello
Run Code Online (Sandbox Code Playgroud)

发送数据

通过JQuery获取请求

请参阅:http://api.jquery.com/jQuery.get/

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

通过JQuery POST请求

请参阅:http://api.jquery.com/jQuery.post/

$.post("test.php", { name: "John"} );
Run Code Online (Sandbox Code Playgroud)

通过Javascript位置获取请求

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

<input type=button 
value="insert button text here"
onClick="self.location='Your_URL_here.php?name=hello'">
Run Code Online (Sandbox Code Playgroud)

读取数据(PHP)

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

有用的链接

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