简体   繁体   中英

call php function onclick

I am working with html / php and I would like to realize the following situation:

在此处输入图片说明

If I click on the "green" button, it should start a php function with the parameter startLoop(5)

If I click on the "red" button, it should start a php function with the parameter startLoop(10)

<?php
function startLoop($loops) {
   for ($x = 0; $x < $loops; $x++) {
      $array[] = $x;
   }
   return $array;
}
?>

the orange area should show the result of the call functions linke this:

<?php
/** orange Area - all values of the array **/
for ($x = 0; $x < count($array); $x++) {
  echo $array[$x];
}
?>

and now is my problem, that i don't know, how I can realize it. This all should happen without a site reload.

Can anybody help me?

index.html

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <button onclick="loop(5)">Green</button><br/>
        <button onclick="loop(10)">Red</button><br/>

        <input type="text" />

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>
            //$.get(url, data, callback)

            function loop(loopsFunctionParameter) {
                $.get(
                    "ajax.php",
                    {
                        loopsFromGet: loopsFunctionParameter
                    },
                    function(result) {
                        $("input").val(result);
                    }
                );
            }
        </script>
    </body>
</html>

ajax.php

<?php
    function startLoop($loops) {
       for ($x = 0; $x < $loops; $x++) {
          $array[] = $x;
       }
       return $array;
    }

    if(isset($_GET["loopsFromGet"])) {
        $result = startLoop($_GET["loopsFromGet"]);
        echo json_encode($result);
    }

We have a JavaScript function that accepts the parameter loops and then it sends the GET request to the ajax.php script and passes the same parameter it accepts. ajax.php returns an array in JSON format but it can be anything really.

Notice: JavaScript is perfectly capable of doing the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM