Background: No php framework is used
Due to temporary needs, I need ajax to call methods in php. I simply wrote a php file. The file defines two methods. How to use ajax to call different methods of the same php file.
The following is the abc.php file. The two methods I defined, a method and b method
<code><span><span><?php</span><span><span>class</span><span>abc</span> {</span><span><span>function</span><span>a</span><span>()</span>{</span><span>echo</span> something; } <span><span>function</span><span>b</span><span>(<span>$args</span>)</span>{</span><span>echo</span> something; } } } <span>?></span></span></code>
The following is Controller.php. This file is a controller that calls other specific functional classes and plays a pivotal role, mainly through reflection. When implementing
<code><span><span><?php</span><span>if</span> (!<span>empty</span>(<span>$_REQUEST</span>[<span>'action'</span>])) { <span>try</span> { <span>$action</span> = explode(<span>'/'</span>, <span>$_REQUEST</span>[<span>'action'</span>]); <span>$class_name</span> = <span>$action</span>[<span>0</span>]; <span>$method_name</span> = <span>$action</span>[<span>1</span>]; <span>require</span><span>$class_name</span> . <span>'.php'</span>; <span>$class</span> = <span>new</span> ReflectionClass(<span>$class_name</span>); <span>if</span> (class_exists(<span>$class_name</span>)) { <span>if</span> (<span>$class</span>->hasMethod(<span>$method_name</span>)) { <span>$func</span> = <span>$class</span>->getmethod(<span>$method_name</span>); <span>$instance</span> = <span>$class</span>->newInstance(); <span>$func</span>->invokeArgs(<span>$instance</span>, <span>array</span>(<span>$_REQUEST</span>)); } } } <span>catch</span> (<span>Exception</span><span>$exc</span>) { <span>echo</span><span>$exc</span>->getTraceAsString(); } } <span>?></span></span></span></code>
using ajax, use the following writing method to only call the a method in abc.php:
<code>$.ajax({ type:<span>"POST"</span>, url: <span>'Controller.php?action=abc/a'</span>, dataType: <span>'json'</span>, success: <span><span>function</span><span>(data)</span> {</span> } });</code>
If you need to pass parameters, you can call it like this:
<code>$.ajax({ <span><span>type</span>:"<span>POST</span>",</span> url: '<span>Controller</span>.php', <span><span>data</span>:<span>{ <span>action</span>=<span>abc</span>/<span>b</span>, 参数1: 123, 参数2: 456}</span></span> dataType: 'json', success: function(<span><span>data</span>) <span>{ }</span></span> });</code>
The above introduces the implementation of PHP modularization for front-end ajax calls, including the content of ajax and PHP. I hope it will be helpful to friends who are interested in PHP tutorials.