使用 onclick 执行 PHP 函数 [英] Execute PHP function with onclick
问题描述
我正在寻找一种简单的解决方案来调用 PHP 函数,仅当点击 a-tag 时.
I am searching for a simple solution to call a PHP function only when a-tag is clicked.
PHP:
function removeday() { ... }
HTML:
<a href="" onclick="removeday()" class="deletebtn">Delete</a>
更新:html 和 PHP 代码在同一个 PHP 文件中
UPDATE: the html and PHP code are in the same PHP file
推荐答案
首先,要了解您同时使用三种语言:
First, understand that you have three languages working together:
PHP:它仅由服务器运行并响应诸如单击链接 (GET) 或提交表单 (POST) 之类的请求.
PHP: It only runs by the server and responds to requests like clicking on a link (GET) or submitting a form (POST).
HTML &JavaScript:它只在某人的浏览器中运行(不包括 NodeJS).
HTML & JavaScript: It only runs in someone's browser (excluding NodeJS).
我假设您的文件类似于:
I'm assuming your file looks something like:
<!DOCTYPE HTML>
<html>
<?php
function runMyFunction() {
echo 'I just ran a php function';
}
if (isset($_GET['hello'])) {
runMyFunction();
}
?>
Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</html>
因为 PHP 只响应请求(GET、POST、PUT、PATCH 和 DELETE,通过 $_REQUEST),所以即使它们在同一个文件中,您也必须运行 PHP 函数.这为您提供了一定程度的安全性,我是否应该为此用户运行此脚本?".
Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST), this is how you have to run a PHP function even though they're in the same file. This gives you a level of security, "Should I run this script for this user or not?".
如果您不想刷新页面,可以通过称为异步 JavaScript 和 XML (AJAX) 的方法在不刷新的情况下向 PHP 发出请求.
If you don't want to refresh the page, you can make a request to PHP without refreshing via a method called Asynchronous JavaScript and XML (AJAX).
不过,您可以在 YouTube 上查找.只需搜索jquery ajax"
That is something you can look up on YouTube though. Just search "jquery ajax"
我向任何刚开始的新手推荐 Laravel:http://laravel.com/
I recommend Laravel to anyone new to start off right: http://laravel.com/
这篇关于使用 onclick 执行 PHP 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!