使用 onclick 执行 PHP 函数

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

Execute PHP function with onclick

javascriptphpajaxonclick

提问by Mike

I am searching for a simple solution to call a PHP functiononly when a-tagis clicked.

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

PHP:

PHP:

function removeday() { ... }

HTML:

HTML:

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

UPDATE:the html and PHP code are in the same PHP file

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

回答by Michael J. Calkins

First, understand that you have three languages working together:

首先,要了解您同时使用三种语言:

  • PHP: It only runs by the server and responds to requests like clicking on a link (GET) or submitting a form (POST).

  • HTML & JavaScript: It only runs in someone's browser (excluding NodeJS).

  • PHP:它仅由服务器运行并响应诸如单击链接 (GET) 或提交表单 (POST) 之类的请求。

  • HTML & JavaScript:它只在某人的浏览器中运行(不包括 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>

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

因为 PHP 只响应请求(GET、POST、PUT、PATCH 和 DELETE,通过 $_REQUEST),这就是您必须运行 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).

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

That is something you can look up on YouTube though. Just search "jquery ajax"

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

I recommend Laravel to anyone new to start off right: http://laravel.com/

我向任何新手推荐 Laravel:http://laravel.com/

回答by devo

In javascript, make an ajax function,

在javascript中,制作一个ajax函数,

function myAjax() {
      $.ajax({
           type: "POST",
           url: 'your_url/ajax.php',
           data:{action:'call_this'},
           success:function(html) {
             alert(html);
           }

      });
 }

Then call from html,

然后从html调用,

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

And in your ajax.php,

在你的 ajax.php 中,

if($_POST['action'] == 'call_this') {
  // call removeday() here
}

回答by A.O.

You will have to do this via AJAX. I HEAVILY reccommend you use jQuery to make this easier for you....

您将必须通过AJAX执行此操作。我强烈建议您使用 jQuery 来使这对您更容易....

$("#idOfElement").on('click', function(){

    $.ajax({
       url: 'pathToPhpFile.php',
       dataType: 'json',
       success: function(data){
            //data returned from php
       }
    });
)};

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

回答by Vamps

It can be done and with rather simple php if this is your button

如果这是您的按钮,则可以使用相当简单的 php 完成

<input type="submit" name="submit>

and this is your php code

这是你的 php 代码

if(isset($_POST["submit"])) { php code here }

the code get's called when submit get's posted which happens when the button is clicked.

当提交 get 发布时调用代码 get,这在单击按钮时发生。

回答by Simpel

Try to do something like this:

尝试做这样的事情:

<!--Include jQuery-->
<script type="text/javascript" src="jquery.min.js"></script> 

<script type="text/javascript"> 
function doSomething() { 
    $.get("somepage.php"); 
    return false; 
} 
</script>

<a href="#" onclick="doSomething();">Click Me!</a>

回答by Kamil Kie?czewski

Solution without page reload

无需重新加载页面的解决方案

<?php
  function removeday() { echo 'Day removed'; }

  if (isset($_GET['remove'])) { return removeday(); }
?>


<!DOCTYPE html><html><title>Days</title><body>

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

  <script>
  async function removeday(e) {
    e.preventDefault(); 
    document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
  }
  </script>

</body></html>

回答by andyNilson

Here′s an alternative with AJAX but no jQuery, just regular JavaScript:

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

Add this to first/main php page, where you want to call the action from, but change it from a potential atag (hyperlink) to a buttonelement, so it does not get clicked by any bots or malicious apps (or whatever).

将此添加到第一个/主 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>

When the buttonis clicked, onclickuses the the head′s javascript function to send $sendingValuevia ajax to another php-page, like many examples before this one. The other page, ajax-php-page.php, checks for the GET value and returns with print_r:

button点击 时,onclick使用 head 的 javascript 函数$sendingValue通过 ajax发送到另一个 php 页面,就像之前的许多示例一样。另一个页面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...");
  }

?>

The response from print_ris then returned and displayed with

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 pelement "results".

+=填充并增加了现有的HTML元素,除去+刚刚更新和替换HTML的现有内容p元素"results"

回答by csandreas1

This is the easiest possible way. If form is posted via post, do php function. Note that if you want to perform function asynchronously (without the need to reload the page), then you'll need AJAX.

这是最简单的方法。如果表单是通过 post 发布的,请执行 php 功能。请注意,如果您想异步执行功能(无需重新加载页面),那么您将需要 AJAX。

<form method="post">
    <button name="test">test</button>
</form>

    <?php
    if(isset($_POST['test'])){
      //do php stuff  
    }
    ?>

回答by Vidya

Try this it will work fine.

试试这个它会工作得很好。

<script>
function echoHello(){
 alert("<?PHP hello(); ?>");
 }
</script>

<?PHP
FUNCTION hello(){
 echo "Call php function on onclick event.";
 }

?>

<button onclick="echoHello()">Say Hello</button>