如何在客户端获取php函数输出?

问题描述 投票:1回答:2

我试图在html(客户端)按钮单击时执行PHP函数(服务器端)。我想将一个参数作为名称传递给PHP函数,作为回报,我希望输出为Hello name。我试过了,但它没有显示,

服务器端 PHP文件名是“name.php”,其功能greet()与参数$name如下:

<?php
function greet($name)
{
   echo "hello $name";
}
?>

客户端 HTML文件包含一个按钮“Click me”,它应该将名称John发送到PHP页面,greet()函数应该执行并输出应该在客户端显示为“Hello John”如下:

<html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
  $("#button").click(function(){
    $.ajax({
      type: "POST",
      url: "name.php",
      data: { name: "John" }
    }).done(greet(data) 
    {
      alert( "Data Saved: " + data);
    }); 
 });
});
</script>

<input type="button" id="button" value="Click me">

</html>

我已经使用Ajax方法调用PHP函数,如果任何其他POST方法可以给出输出,那么请让我知道。 有人可以帮助如何在按钮点击时从PHP功能输出到客户端。

php html ajax html5 client-server
2个回答
1
投票

你不能从JavaScript调用PHP函数,甚至从Ajax调用。 Ajax的作用是询问从PHP文件输出的数据。因此,您需要在name.php中调用该函数,该函数提供输出 - 然后您可以在PHP中打印。

Ajax只会获取从PHP打印的字符串。

另请注意,您不需要通过在文件末尾执行?>来关闭PHP,除非有一些HTML或类似的内容。

服务器端,你会做这样的事情

<?php
// Define the function
function greet($name) {
   return "Hello $name";
}

// Call the function with the value sent from Ajax - this output is what Ajax fetches
echo greet($_POST['name']);

客户端你会做类似的事情

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    $("#button").on("click", function() {
      $.ajax({
        type: "POST",
        url: "name.php",
        data: { name: "John" }
      }).done(data) {
        alert("Data Saved: " + data);
      }); 
    });
</script>

<input type="button" id="button" value="Click me">

然后data将包含从PHP文件打印的所有字符串。如果您期望一个数组,则需要将其转换为JSON。


0
投票

首先,您需要在单击按钮时绑定ajax调用,因此当按钮单击它时将触发ajax调用。

$(document).ready(function()
{
// when button click it will trigger ajax call
 $("#button").click(function(){
     $.ajax({
         type: "GET",
         url: "name.php",
         data: { name: "John" },
         success: function(data) {
            // on successfull return it will alert the data 
            alert("Data saved: " + data);
         }    
      });
  });
});

并在你的名字.php

 <?php
    // get your data you send from ajax 
   $name = $_GET['name'];
   // it will echo the "hello $name" and return it
   greet($name);

   function greet($name)
   {
     echo "hello $name";
   }
 ?>
© www.soinside.com 2019 - 2024. All rights reserved.