簡體   English   中英

單擊html按鈕調用PHP函數

[英]Call PHP function on click of a html button

我想在單擊按鈕后調用php函數。 我已經找到了一種方法(有點)。

這是我的代碼:

info.html

<html>
 <head>    
 </head>
 <body>  

<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main'">

 </body>
</html>

info.php

<?php    

    if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
    call_user_func($_GET['runFunction']);
    else
    echo "Function not found or wrong input";

    function readCSV($csvFile){
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle ,1024,";");
    }
    fclose($file_handle);
    return $line_of_text;
    }

    function main($csvFile){

        //Set path to CSV File

        $csv = readCSV($csvFile);
        echo '<pre>';
        print_r($csv);
        echo '</pre>';

    }  


?>

我的按鈕可以調用主函數,但是我不知道如何通過單擊按鈕來傳遞變量,有人可以幫我嗎?

您可以將參數作為另一個URL參數傳遞:

<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main&arguments[]=File.csv'">

然后,PHP將是:

if(isset($_GET['runFunction']) && function_exists($_GET['runFunction'])) {
    if (isset($_GET['arguments'])) {
        $args = $_GET['arguments'];
    } else {
        $args = array();
    }
    call_user_func_array($_GET['runFunction'], args);
} else {
    echo "Function not found or wrong input";
}

在URL中的參數名稱后放置[] ,將告訴PHP將具有相同名稱的所有參數收集到一個數組中。

但是,這非常危險,因為它允許某人執行任何PHP函數。 有人可以連接到諸如info.php?runFunction=unlink&arguments[]=.htaccess類的URL。

您應該對照允許調用的函數列表檢查函數名稱。

您必須撥打AJAX電話 您可以通過GET或POST方法在其中傳遞任何參數。 AJAX是執行此操作的最簡單方法。

您應該使用Ajax將數據發送到服務器

<script>

function sendData(){
  var data1 = "Hello";
  var data2 = "World";
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function(){
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        alert(xmlhttp.responseText);
  }
  xmlhttp.open("GET", "ajax.php?data1=" + data1 + "&data2=" + data2, true);
  xmlhttp.send();
}

</script>

單擊按鈕后,您將調用sendData函數:

<input type=button value="test" onClick="sendData()">

服務器讀取GET參數

if(isset($_GET['data1']) && isset($_GET["data2"])){
  $data1 = $_GET["data1"];
  $data2 = $_GET["data2"];

  return $data1 . " " . $data2 . " was sent to the server";
}

更改

<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main'"

<a href="info.php?runFunction=main"><input type=button value="test"></a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM