使用 onclick 执行 PHP 函数

新手上路,请多包涵

我正在寻找一个简单的解决方案,仅在单击 a-tag 时调用 PHP 函数

PHP:

 function removeday() { ... }

HTML:

 <a href="" onclick="removeday()" class="deletebtn">Delete</a>

更新: html 和 PHP 代码在同一个 PHP 文件中

原文由 Mike 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 929
2 个回答

首先,了解您有三种语言协同工作:

  • PHP:它只由服务器运行并响应点击链接(GET)或提交表单(POST)等请求。

  • HTML & JavaScript:它只能在某人的浏览器中运行(不包括 NodeJS)。

我假设您的文件看起来像:

 <!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 函数的方式。这为您提供了一定程度的安全性,“我应该为这个用户运行这个脚本吗?”。

如果您不想刷新页面,您可以通过称为异步 JavaScript 和 XML (AJAX) 的方法向 PHP 发出请求而无需刷新。

不过,这是您可以在 YouTube 上查找的内容。只需搜索“jquery ajax”

我向任何刚开始的新手推荐 Laravel: http ://laravel.com/

原文由 Michael J. Calkins 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是 AJAX 的替代方案,但没有 jQuery,只有常规的 JavaScript:

将此添加到您要从中调用操作的第一个/主 php 页面,但将其从潜在的 a 标签(超链接)更改为 button 元素,所以它不会被任何机器人或恶意应用程序(或其他)点击。

 <head>
<script>
  // function invoking ajax with pure javascript, no jquery required.
  function myFunction(value_myfunction) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("results").innerHTML += this.responseText;
        // note '+=', adds result to the existing paragraph, remove the '+' to replace.
      }
    };
    xmlhttp.open("GET", "ajax-php-page.php?sendValue=" + value_myfunction, true);
    xmlhttp.send();
  }

</script>
</head>

<body>

  <?php $sendingValue = "thevalue"; // value to send to ajax php page. ?>

  <!-- using button instead of hyperlink (a) -->
  <button type="button" onclick="value_myfunction('<?php echo $sendingValue; ?>');">Click to send value</button>

  <h4>Responses from ajax-php-page.php:</h4>
  <p id="results"></p> <!-- the ajax javascript enters returned GET values here -->

</body>

当点击 button 时, onclick 使用头部的 javascript 函数发送 $sendingValue 通过 ajax 到另一个 php-page .另一页 ajax-php-page.php 检查 GET 值并返回 print_r

 <?php

  $incoming = $_GET['sendValue'];

  if( isset( $incoming ) ) {
    print_r("ajax-php-page.php recieved this: " . "$incoming" . "<br>");
  } else {
    print_r("The request didn´t pass correctly through the GET...");
  }

?>

然后返回来自 print_r 的响应并显示为

document.getElementById("results").innerHTML += this.responseText;

The += populates and adds to existing html elements, removing the + just updates and replaces the existing contents of the html p element "results" .

原文由 andiOak 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题