is divided into 3 parts to complete the ajax calling logic of php. The following is the general structure
Part one: ajax request: mainly the action parameter, LoginController is the class name of php, login is the function name in the LoginController class
$('#submit').on('click', function (e) { e.stopPropagation(); $.ajax({ url: "../../controllers/Controller.php", data: { action: "LoginController/login", username: username, password: password }, dataType: "text", type: 'POST', timeout: 10000, error: function () { alert("服务器超时"); }, success: function (data) { alert(data); } }); });
Part 2: Controller.php, this file is to call controllers of other specific functional classes and plays a pivotal role, mainly through reflection
<?php if (!empty($_REQUEST['action'])) { try { $action = explode('/', $_REQUEST['action']); $class_name = $action[0]; $method_name = $action[1]; require $class_name . '.php'; $class = new ReflectionClass($class_name); if (class_exists($class_name)) { if ($class->hasMethod($method_name)) { $func = $class->getmethod($method_name); $instance = $class->newInstance(); $func->invokeArgs($instance, array($_REQUEST)); $result = $instance->getResult(); echo $result; } } } catch (Exception $exc) { echo $exc->getTraceAsString(); } } ?>
The third part: LoginController.php, this file is a specific functional class
<?php class LoginController { private $result; function LoginController() { //初始化数据库连接等参数 } function login($args) { //具体的登录逻辑 } function getResult() { return $this->result; } } ?>
That’s all the content of this article, I hope you all like it.