背景:沒有使用php框架
由於臨時需求,需要ajax呼叫php中的方法,簡單的寫了一個php文件,文件定義了兩個方法,如何用ajax分別呼叫同一個php文件不同的方法。
以下是abc.php文件,我定義的兩個方法a方法和b方法
<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>
以下是Controller.php,這個文件是調用其他特定的功能類的控制器,起到樞紐作用,主要是透過反射來實作
<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>
使用ajax呼叫時,使用如下寫法實作只呼叫abc.php中的a方法:
<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>
如果需要傳參數,可以這麼寫來呼叫:
<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>').addClass('pre-numbering' ).hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });
以上就介紹了php模組化供前端ajax呼叫的實現,包括了ajax,php方面的內容,希望對PHP教程有興趣的朋友有幫助。