2016-08-26 106 views
0

我想獲得函數的返回值並將其顯示爲特定的ID。PHP函數返回值爲html標記

在我Class.php我有一個函數命名登錄,它驗證,如果密碼正確/不正確

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

,並在我的index.php我我有這個網站。現在我怎樣才能得到我的登錄函數的返回值在我的HTML標籤

<?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> 
+1

'<?php echo $ class-> login();?>' – RiggsFolly

+1

但是你真的應該做自己的功課 – RiggsFolly

回答

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> 
+0

實際上並不保證可以工作 – RiggsFolly

+0

如果我有很多返回值,如果這樣做會怎樣。密碼不正確,用戶名不正確。 – Fate

0

我沒有測試過下面的代碼檢查的ID,但是你可以用這個邏輯來實現你的目標。

你的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(); 
?>