thinkphp5дapi½Ó¿ÚÇëÇó·µ»Ø
Ëæ×Å»¥ÁªÍøµÄÆÕ¼°£¬web¿ª·¢µÄÐèÇóÒ²Ô½À´Ô½¶à¡£ÔÚweb¿ª·¢ÖУ¬api½Ó¿Ú³ÉÁ˲»¿É»òȱµÄÒ»²¿·Ö£¬¶øÔÚphpÁìÓò£¬thinkphp5ÎÞÒÉÊÇ×îÊ¢ÐеĿò¼ÜÖ®Ò»¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃthinkphp5¿ò¼ÜÀ´±àдapi½Ó¿ÚÇëÇóºÍ·µ»Ø¡£
Ò»¡¢API½Ó¿ÚÇëÇó
1.1 GETÇëÇó
ÔÚthinkphp5ÖУ¬Ê¹ÓÃGETÇëÇó·¢ËÍAPIÇëÇóºÜÊǼòÆÓ¡£ÒÔÏÂÊÇÒ»¸öʾÀý´úÂ룺
use thinkRequest; $request = Request::instance(); $name = $request->get('name'); $age = $request->get('age'); //×ö³öÏìÓ¦
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂëÖУ¬ÎÒÃÇʹÓÃÁËRequestÀàµÄʵÀý»¯¹¤¾ß£¬È»ºóʹÓÃgetÒªÁì»ñÈ¡ÇëÇó²ÎÊý¡£½ÓÏÂÀ´¿ÉÒÔ¶Ô²ÎÊý¾ÙÐÐÏìÓ¦¡£
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
1.2 POSTÇëÇó
ÔÚthinkphp5ÖУ¬Ê¹ÓÃPOSTÇëÇó·¢ËÍAPIÇëÇóµÄÒªÁìºÍGETÇëÇó»ùÄÚÇéͬ¡£ÒÔÏÂÊÇÒ»¸öʾÀý´úÂ룺
use thinkRequest; $request = Request::instance(); $name = $request->post('name'); $age = $request->post('age'); //×ö³öÏìÓ¦
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂëÖУ¬ÎÒÃÇͬÑùʹÓÃÁËRequestÀàµÄʵÀý»¯¹¤¾ß£¬È»ºóʹÓÃpostÒªÁì»ñÈ¡ÇëÇó²ÎÊý¡£½ÓÏÂÀ´¿ÉÒÔ¶Ô²ÎÊý¾ÙÐÐÏìÓ¦¡£
1.3 JSONÇëÇó
ÔÚAPI¿ª·¢ÖУ¬JSONÇëÇóÒ²ÊǷǾ³£¼ûµÄÒ»ÖÖ·½·¨£¬³ýÁËGETºÍPOSTÇëÇó£¬thinkphp5»¹ÌṩÁ˽ÓÊܺÍÏìÓ¦JSONÊý¾ÝµÄÒªÁì¡£ÒÔÏÂÊÇÒ»¸öʾÀý´úÂ룺
use thinkRequest; $request = Request::instance(); $data = $request->getContent(); $json = json_decode($data, true); $name = $json['name']; $age = $json['age']; //×ö³öÏìÓ¦
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂëÖУ¬ÎÒÃÇÊ×ÏÈʹÓÃgetContentÒªÁì»ñÈ¡ÇëÇóÌåÖеÄJSONÊý¾Ý£¬È»ºóʹÓÃjson_decode½«JSON×Ö·û´®×ª»¯ÎªÊý×é¡£½ÓÏÂÀ´¶ÔÊý×é¾ÙÐвÙ×÷»òÏìÓ¦¡£
¶þ¡¢API½Ó¿Ú·µ»Ø
ÔÚ¿ª·¢API½Ó¿Úʱ£¬·µ»ØÊý¾ÝͬÑùºÜÊÇÖ÷Òª¡£ÎÒÃÇͨ³£ÐèÒª·µ»ØjsonÊý¾Ý£¬ÒÔÏÂÊÇÒ»¸öʾÀý´úÂ룺
use thinkController; class ApiController extends Controller { public function index() { //Êý¾ÝÊý×é $result = [ 'code' => 0, 'msg' => 'success', 'data' => [ 'name' => 'test', 'age' => 18 ] ]; //·µ»ØjsonÊý¾Ý return json($result); } }
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂëÖУ¬ÎÒÃÇÊ×ÏȽç˵·µ»ØÊý¾ÝµÄÊý×飬ȻºóʹÓÃjsonº¯Êý½«Êý×éת»¯Îªjson×Ö·û´®·µ»Ø¡£
Èý¡¢×ܽá
±¾ÎÄÖУ¬ÎÒÃÇÏÈÈÝÁËÔõÑùʹÓÃthinkphp5¿ò¼ÜÀ´±àдAPI½Ó¿ÚÇëÇóºÍÏìÓ¦¡£ÔÚÏÖʵ¿ª·¢ÖУ¬ÎÒÃÇ»¹ÐèҪעÖؽӿÚÇëÇóµÄÇå¾²ÐÔ¡¢Êý¾ÝÃûÌõÈÎÊÌ⡣ϣÍû±¾ÎÄÄܹ»¶Ô¶ÁÕßÓÐËù×ÊÖú£¬Îª¸÷È˵ÄAPI¿ª·¢ÌṩһЩ×ÊÖú¡£
ÒÔÉϾÍÊÇthinkphp5дapi½Ó¿ÚÇëÇ󷵻صÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡