AJAX怎样调用php内的一个函数

HTML表单:
\u0026lt;form class="foo" action="cl.php?action=foo" method="post"\u0026gt;\t\u0026lt;input type="text" name="t1" /\u0026gt;\t\u0026lt;input type="text" name="t2" /\u0026gt;\t\u0026lt;input type="submit" value="https://www.zhihu.com/api/v4/questions/56349467/提交" /\u0026gt;\u0026lt;/form\u0026gt;\u0026lt;form class="bar" action="cl.php?action=bar" method="post"\u0026gt;\t\u0026lt;input type="text" name="t1" /\u0026gt;\t\u0026lt;input type="text" name="t2" /\u0026gt;\t\u0026lt;input type="submit" value="https://www.zhihu.com/api/v4/questions/56349467/提交" /\u0026gt;\u0026lt;/form\u0026gt;\u0026lt;script\u0026gt;jQuery.noConflict();(function($){\t$(document).ready(function(){\t\t// 处理foo操作\t\t$(document).on("submit", "form.foo", function(e){\t\t\te.preventDefault();\t\t\t$.ajax({\t\t\t\turl: this.action,\t\t\t\ttype: this.method,\t\t\t\tdata: $(this).serialize(), // 能自动拿到表单里的input参数t1和t2\t\t\t\tdataType: "json"\t\t\t}).done(function(data){\t\t\t\talert("请求成功");\t\t\t\t// 处理服务器返回的JSON数据\t\t\t\tconsole.log(data);\t\t\t}).fail(function(){\t\t\t\talert("请求失败");\t\t\t});\t\t});\t\t// 处理bar操作\t\t$(document).on("submit", "form.bar", function(e){\t\t\te.preventDefault();\t\t\t$.ajax({\t\t\t\turl: this.action,\t\t\t\ttype: this.method,\t\t\t\tdata: $(this).serialize(), // 能自动拿到表单里的input参数t1和t2\t\t\t\tdataType: "json"\t\t\t}).done(function(data){\t\t\t\talert("请求成功");\t\t\t\t// 处理服务器返回的JSON数据\t\t\t\tconsole.log(data);\t\t\t}).fail(function(){\t\t\t\talert("请求失败");\t\t\t});\t\t});\t});})(jQuery);\u0026lt;/script\u0026gt;PHP控制器(cl.php):
\u0026lt;?php// 处理foo操作: cl.php?action=fooif (isset($_GET) \u0026amp;\u0026amp; $_GET === \u0026#39;foo\u0026#39;) {\t// 处理HTML表单,返回JSON\theader(\u0026#39;Content-Type: application/json; charset=utf-8\u0026#39;);\techo json_encode($_POST);}// 处理bar操作: cl.php?action=barif (isset($_GET) \u0026amp;\u0026amp; $_GET === \u0026#39;bar\u0026#39;) {\t// 处理HTML表单,返回JSON\theader(\u0026#39;Content-Type: application/json; charset=utf-8\u0026#39;);\techo json_encode($_POST);}你也可以考虑把上面这2个action操作的处理封装成类的2个方法method:
\u0026lt;?phpclass io_cl {\t/**\t * 控制器默认动作方法(action =\u0026gt; method)\t * cl.php?action=index\t */\tpublic function index() {\t\t// 输出HTML表单\t\theader(\u0026#39;Content-Type: text/html; charset=utf-8\u0026#39;);\t\techo io_render(\u0026#39;cl.php\u0026#39;);\t}\t/*\t * 处理foo操作\t * cl.php?action=foo\t */\tpublic function foo() {\t\t// 处理HTML表单,返回JSON\t\theader(\u0026#39;Content-Type: application/json; charset=utf-8\u0026#39;);\t\techo json_encode($_POST);\t}\t/*\t * 处理bar操作\t * cl.php?action=bar\t */\tpublic function bar() {\t\t// 处理HTML表单,返回JSON\t\theader(\u0026#39;Content-Type: application/json; charset=utf-8\u0026#39;);\t\techo json_encode($_POST);\t}}// 运行控制器io_run(\u0026#39;io_cl\u0026#39;);其中io_run和io_render的实现如下:


推荐阅读