使用onclick执行PHP函数

时间:2013-10-11 16:31:02

标签: javascript php ajax onclick

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

PHP:

function removeday() { ... }

HTML:

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

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

9 个答案:

答案 0 :(得分:126)

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

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

  • HTML&amp; JavaScript:仅在某人的浏览器中运行(不包括NodeJS)。

我假设您的文件类似于:

<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只响应请求(通过$ _REQUEST获取GET,POST,PUT,PATCH和DELETE),所以即使它们在同一个文件中,也必须运行PHP函数。这为您提供了一定程度的安全性,“我是否应该为此用户运行此脚本?”。

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

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

我向所有新人开始推荐Laravel:http://laravel.com/

答案 1 :(得分:34)

在javascript中,创建一个ajax函数,

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

      });
 }

然后从html调用,

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

在你的ajax.php中,

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

答案 2 :(得分:12)

您必须通过 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/

答案 3 :(得分:9)

它可以用相当简单的PHP完成 如果这是你的按钮

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

这是你的php代码

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

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

答案 4 :(得分:1)

尝试做这样的事情:

<!--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>

答案 5 :(得分:1)

这里是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使用head的javascript函数通过ajax将$sendingValue发送到另一个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...");
  }

?>

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

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

+=会填充并添加到现有的html元素中,而删除+只会更新并替换html p元素"results"的现有内容。

答案 6 :(得分:0)

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

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

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

答案 7 :(得分:0)

试试这个它会正常工作。

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

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

?>

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

答案 8 :(得分:0)

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

<?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>
相关问题