Home > Article > Backend Development > PHP implements control of all background function calls based on ajax
This article mainly introduces PHP to control all background function calls based on Ajax. Friends who are interested can refer to it. I hope it will be helpful to everyone.
It is divided into 3 parts to complete the ajax call logic of php. The following is the general structure.
The first part: ajax request: mainly the action parameter, LoginController is the class name of php, login It 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); } }); });
The second part: Controller.php, this file is the controller that calls 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; } } ?>
Summary:The above is the entire content of this article, I hope it can be useful for everyone's learning. helped.
Related recommendations:
Word guessing game implemented in php
Using php questionnaire survey results statistics
How to use php to automatically execute .sql files
The above is the detailed content of PHP implements control of all background function calls based on ajax. For more information, please follow other related articles on the PHP Chinese website!