【问题标题】:PHP function return value to html tagPHP函数返回值到html标签
【发布时间】:2016-08-26 08:13:05
【问题描述】:

我想获取一个函数的返回值并显示到一个特定的id。

在我的 Class.php 中,我有一个名为 login 的函数,用于验证密码是否正确/不正确

<?php
class Class
{
    public function login()
    {
        if($_POST['password'] == Match) {
            return 'Correct Password!';
        } else {
            return 'Incorrect password!';
        }
    }
}

在我的 index.php 中有这个 html。现在如何在我的 html 标记中获取我的登录函数的返回值,ID 为 check

<?php
require_once 'Class.php';
$class = new Class();
$class->login();
?>

<!DOCTYPE html>
<html>
<head>
    <title>SOMETHING</title>
</head>
<body>
    <form action="" method="POST">
        <input type="text" name="username">
        <input type="password" name="password">
        <span id="check"></span> <!-- I want to put the returned value here -->

        <input type="submit" value="Login">
    </form>

</body>
</html>

【问题讨论】:

  • &lt;span id="check"&gt;&lt;?php echo $class-&gt;login();?&gt;&lt;/span&gt;
  • 但是你真的应该做自己的功课

标签: php html


【解决方案1】:
<?php
require_once 'Class.php';
$class = new Class();
$returnedValue = $class->login();
?>

<!DOCTYPE html>
<html>
<head>
    <title>SOMETHING</title>
</head>
<body>
    <form action="" method="POST">
        <input type="text" name="username">
        <input type="password" name="password">
        <span id="check"><?= $returnedValue ?></span>

        <input type="submit" value="Login">
    </form>

</body>
</html>

【讨论】:

  • 如果我有很多返回值,比如。密码错误,用户名错误。
【解决方案2】:

我没有测试过下面的代码,但是你可以使用这个逻辑来实现你的目标。

您的 index.php 文件:

<!DOCTYPE html>
<html>
<head>
    <title>SOMETHING</title>
</head>
<body>
    <form class="loginform" action="" method="POST">
        <input type="text" name="username">
        <input type="password" name="password">
        <span id="check"></span>

        <input type="submit" value="Login"  class="Login">
    </form>

</body>
</html>

您的 Ajax 脚本(使用 jquery):

 $(function() {
      $("button.Login").click(function(){
              $.ajax({
              type: "POST",
              url: "data.php",
              data: $('form.loginform').serialize(),
              success: function(msg){
                 $('#check').html(msg);
                  },
                });
      });
  });

你要接收数据的php文件(data.php):

<?php
require_once 'Class.php';
$class = new Class();
echo $class->login();
?>

【讨论】:

    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多