laravel ÅжÏÊÇ·ñajax
laravelÊÇÒ»ÖÖÊ¢ÐеÄphp¿ò¼Ü£¬¾ßÓи߶ȿÉÀ©Õ¹ÐÔºÍÎÞаÐÔ¡£¸Ã¿ò¼ÜÌṩÁËÐí¶àÊÊÓõÄÄÚÖÃÒªÁìºÍº¯Êý£¬ÒÔ±ãÎÒÃǸüÇáËɵع¹½¨webÓ¦ÓóÌÐò¡£ÔÚ¿ª·¢webÓ¦ÓóÌÐòʱ£¬javascriptÊÇÒ»¸öºÜÊÇÒªº¦µÄÊÖÒÕ¡£Í¨³£ÇéÐÎÏ£¬ÎÒÃÇÐèҪʹÓÃajaxÊÖÒÕÀ´ÒÔÇ°¶ËÓëºó¶Ë¾ÙÐÐÊý¾Ý½»»¥¡£ÔÚlaravelÖУ¬ÓÐÒ»¸öºÜÖ÷ÒªµÄÎÊÌâÊÇÔõÑùÅжÏÄ¿½ñÇëÇóÊÇ·ñÊÇajaxÇëÇó¡£ÔÚ±¾ÆªÎÄÕÂÖУ¬ÎÒÃǽ«Ñ§Ï°ÔõÑùʹÓÃlaravelÀ´ÅжÏÄ¿½ñÇëÇóÊÇ·ñÊÇajaxÇëÇó¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÏàʶʲôÊÇAjaxÇëÇó¡£AjaxÊÇÒ»ÖÖÒì²½JavaScriptºÍXMLÊÖÒÕ£¬ËüÔÊÐíͨ¹ýÔÚºǫ́ÓëЧÀÍÆ÷½»Á÷Êý¾ÝÀ´¸üÐÂÒ»¸öWebÒ³ÃæµÄ¾Ö²¿ÄÚÈÝ¡£AjaxÇëÇ󲻻ᵼÖÂÕû¸öÒ³ÃæµÄÖØмÓÔØ£¬Òò´Ë¿ÉÒÔÏÔÖøÌá¸ßWebÓ¦ÓóÌÐòµÄÏìÓ¦ËÙÂʺÍÓû§ÌåÑé¡£ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓá°XMLHttpRequest¡±¹¤¾ßÀ´·¢ËÍAjaxÇëÇó¡£
ÏÖÔÚ£¬ÎÒÃÇÀ´¿´Ò»ÏÂÔÚLaravelÖÐÔõÑùÅжÏÄ¿½ñÇëÇóÊÇ·ñÊÇAjaxÇëÇó¡£LaravelÌṩÁËÒ»¸öÃûΪ¡°request¡±µÄÈ«¾ÖÖúÊÖº¯Êý£¬ÎÒÃÇ¿ÉÒÔʹÓÃÕâ¸öº¯Êý»ñÈ¡Ä¿½ñHTTPÇëÇóµÄʵÀý¡£ÔÚÕâ¸öÇëÇóʵÀýÉÏ£¬LaravelÌṩÁËÒ»¸öÒªÁìÃûΪ¡°ajax¡±£¬Õâ¸öÒªÁì¿ÉÒÔ×ÊÖúÎÒÃÇÅжÏÄ¿½ñÇëÇóÊÇ·ñÊÇAjaxÇëÇó¡£ÈÃÎÒÃÇÀ´¿´Ò»ÏÂÏÂÃæµÄʾÀý´úÂ룺
use IlluminateHttpRequest; Route::get('/test', function (Request $request) { if ($request->ajax()) { return "This is an Ajax request"; } else { return "This is a normal request"; } });
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀý´úÂëÖУ¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪ¡°test¡±µÄ·ÓÉ£¬²¢ÇÒÔÚÕâ¸ö·ÓɵĻص÷º¯ÊýÖУ¬ÎÒÃÇʹÓÃÁË¡°request¡±È«¾ÖÖúÊÖº¯ÊýÀ´»ñÈ¡Ä¿½ñÇëÇóµÄʵÀý¡£½Ó×Å£¬ÎÒÃÇʹÓÃÁË¡°ajax¡±ÒªÁìÀ´ÅжÏÄ¿½ñÇëÇóÊÇ·ñÊÇAjaxÇëÇó¡£ÈôÊÇÊÇAjaxÇëÇó£¬ÎÒÃǽ«·µ»Ø×Ö·û´®¡°This is an Ajax request¡±£¬²»È»·µ»Ø×Ö·û´®¡°This is a normal request¡±¡£
³ýÁËʹÓá°ajax¡±ÒªÁìÖ®Í⣬Laravel»¹ÌṩÁËÒ»ÖÖ½Ð×ö¡°expectsJson¡±µÄÒªÁ죬Õâ¸öÒªÁì¿ÉÒÔ×ÊÖúÎÒÃÇÅжÏÊÇ·ñÓ¦¸Ã·µ»ØJSONÏìÓ¦¡£Õâ¸öÒªÁìÔÚÅжÏÄ¿½ñÇëÇóÊÇ·ñÊÇAjaxÇëÇóʱҲÊǺÜÊÇÓÐÓõġ£ÈÃÎÒÃÇÀ´¿´Ò»ÏÂÏÂÃæµÄʾÀý´úÂ룺
use IlluminateHttpRequest; Route::get('/test', function (Request $request) { if ($request->expectsJson()) { return "This is an Ajax request"; } else { return "This is a normal request"; } });
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀý´úÂëÖУ¬ÎÒÃÇʹÓÃÁË¡°expectsJson¡±ÒªÁìÀ´ÅжÏÄ¿½ñÇëÇóÊÇ·ñÓ¦¸Ã·µ»ØJSONÏìÓ¦¡£ÈôÊÇÓ¦¸Ã·µ»ØJSONÏìÓ¦£¬ÎÒÃǽ«·µ»Ø×Ö·û´®¡°This is an Ajax request¡±£¬²»È»·µ»Ø×Ö·û´®¡°This is a normal request¡±¡£
ÔÚʹÓÃÕâÁ½¸öÒªÁìʱ£¬ÎÒÃÇÐèҪעÖØһЩϸ½Ú¡£ÈôÊÇÎÒÃÇÔÚPHPÎļþµÄ¶¥²¿Ê¹ÓÃÁË¡°use IlluminateHttpRequest¡±Óï¾ä£¬ÄÇôÎÒÃÇÔڻص÷º¯ÊýÖоͿÉÒÔÖ±½ÓʹÓá°Request $request¡±Õâ¸ö²ÎÊýÀ´»ñÈ¡Ä¿½ñÇëÇóµÄʵÀý¡£ÈôÊÇûÓÐʹÓÃÕâ¸öÓï¾ä£¬ÎÒÃÇÐèÒªÕâÑùд£º¡°function (IlluminateHttpRequest $request)¡±¡£
ÁíÍ⣬ÎÒÃÇ»¹ÐèҪעÖØһϡ°ajax¡±ÒªÁìºÍ¡°expectsJson¡±ÒªÁìµÄÇø±ð¡£ÔÚLaravelÖУ¬¡°ajax¡±ÒªÁìÓÃÓÚ¼ì²éÇëÇóÍ·ÎļþÊÇ·ñ°üÀ¨¡°X-Requested-With¡±²ÎÊý£¬ÈôÊÇ°üÀ¨£¬Ôò˵Ã÷Ä¿½ñÇëÇóÊÇAjaxÇëÇ󣻶ø¡°expectsJson¡±·½¹æÔòÓÃÓÚ¼ì²é½ÓÊܵÄÄÚÈÝÀàÐÍÊÇ·ñΪJSON¡£ÈôÊǽÓÊܵÄÄÚÈÝÀàÐÍÊÇJSON£¬ÔòÎÞÂÛÊÇͨË×ÇëÇóÕÕ¾ÉAjaxÇëÇ󣬶¼¿ÉÒÔʹÓá°expectsJson¡±ÒªÁìÅжϡ£Òò´Ë£¬ÔÚÏÖʵӦÓÃÖУ¬ÎÒÃÇÓ¦¸Ãƾ֤ÐèҪѡÔñʹÓÃÄÄÖÖÒªÁì¡£
ÔÚ¿¢Ê±¾ÆªÎÄÕÂ֮ǰ£¬ÎÒÏëÔÙÌáÐÑһ϶ÁÕߣ¬ÅжÏÄ¿½ñÇëÇóÊÇ·ñÊÇAjaxÇëÇóÔÚÐí¶à³¡¾°Ï¶¼ÊǺÜÊÇÖ÷ÒªµÄ£¬Òò´ËÄãÓ¦¸Ã¾¡¿ÉÄܵØÊìÁ·ÕÆÎÕÕâ¸ö¼¼ÇÉ¡£Ï£ÍûÕâƪÎÄÕ¶ÔÄãÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇlaravel ÅжÏÊÇ·ñajaxµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡