繁体   English   中英

调用php函数onclick

[英]call php function onclick

我正在使用html / php,我想了解以下情况:

在此处输入图片说明

如果单击“绿色”按钮,则应该使用参数startLoop(5)启动php函数。

如果单击“红色”按钮,则应该使用参数startLoop(10)启动php函数。

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

橙色区域应显示调用函数的结果,将其链接:

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

现在是我的问题,我不知道该如何实现。 这一切都应该在不重新加载站点的情况下发生。

有谁能够帮助我?

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);
    }

我们有一个JavaScript函数,它接受参数循环 ,然后将GET请求发送到ajax.php脚本,并传递它接受的相同参数。 ajax.php返回JSON格式的数组,但实际上可以是任何东西。

注意:JavaScript完全有能力做同样的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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