$ .post进入php类函数

时间:2014-04-21 17:25:51

标签: php ajax post

我想进行实时用户名检查,我想使用PHP函数。

-->
<?php
    require '../../core/init.php';
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>K&ouml;ppCMS - Registrieren</title>
    <link rel="stylesheet" href="../../../css/style.css">
    <script type="text/javascript" src="../../../js/jquery.js"></script>
    <script type="text/javascript" src="../../../js/footer.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#username").keyup(function (e) {

                //removes spaces from username
                $(this).val($(this).val().replace(/\s/g, ''));

                var username = $(this).val(); //get the string typed by user

                $.post('users.php', {'username':username}, function(data) { //make ajax call to users.php
                    $("#user-result").html(data); //dump the data received from PHP page
                });

            });
        });
</script>
</head>

的init.php:

<?php
session_start();
require 'database/connect.php';
require 'classes/users.php';
require 'classes/general.php';

$users         = new Users($db);
$general     = new General();

$errors     = array();
?>

那么如何调用check_username函数并将值发送给它? 希望你理解我的问题,因为我的英语不太好。

我在users.php中试过这个:

<?php
$users = new Users($db);
echo $users->check_username($_POST['username']);
class Users{
    private $db;

    public function __construct($database) {
        $this->db = $database;
    }

    public function check_username($data) {
        return $data+1;
    }
    function func1($data){
        return $data+1;
    }

}

获取此错误:

Notice: Undefined variable: db in C:\xampp\htdocs\kcms\system\cms\user\users.php on line 2

enter image description here

1 个答案:

答案 0 :(得分:3)

您的PHP脚本应该执行以下操作:

<?php
require('init.php'); // This contains $users = new Users($db);
echo $users->check_username($_POST['username']);

要在Javascript中使用返回值,请参阅

How do I return the response from an asynchronous call?