thinkphp ajaxÊÖÒÕÒ³ÃæÎÞˢеļòÖÊÆÓÏÖ
Ëæ×Å»¥ÁªÍøµÄÉú³¤£¬Ò³ÃæÎÞË¢ÐÂÊÖÒÕ³ÉΪÁËÔ½·¢¸ßЧµÄÍøÒ³¿ª·¢·½·¨£¬¶øajax(asynchronous javascript and xml)ÊÇÆäÖÐÒ»ÖÖʵÏÖ·½·¨¡£±¾ÎĽ«ÏÈÈÝÔõÑùÔÚthinkphpÖÐʵÏÖÎÞˢеÄajaxÊÖÒÕ¡£
1¡¢AJAXÊÖÒÕ¸ÅÊö
AJAXÊÇÒ»ÖÖʹÓÃJavaScriptºÍXMLÊÖÒÕµÄÒ첽ͨѶ·½·¨£¬¿ÉÒÔÔÚÒ³Ã治ˢеÄÇéÐÎÏÂÓëЧÀÍÆ÷¾ÙÐÐÊý¾Ý½»»¥£¬Ìá¸ßÁËÓû§µÄ½»»¥ÌåÑé¡£ÏêϸµØ˵£¬AJAXͨ¹ýXMLHttpRequest¹¤¾ßÏòЧÀÍÆ÷·¢ËÍÇëÇó£¬Ð§ÀÍÆ÷·µ»ØÊý¾ÝºóÔÙͨ¹ýJavaScript¶¯Ì¬ÐÞ¸ÄÒ³ÃæÄÚÈÝ£¬´Ó¶øʵÏÖÒ³ÃæÎÞË¢ÐÂЧ¹û¡£
2¡¢thinkphp¿ò¼ÜµÄ»ù±¾½á¹¹
ÔÚthinkphp¿ò¼ÜÏ£¬ÎÒÃÇÐèÒªÏÈÏàʶÆä»ù±¾½á¹¹¡£thinkphp¿ò¼ÜµÄMVC¼Ü¹¹°üÀ¨Model¡¢ViewºÍControllerÈý¸ö²¿·Ö¡£ÆäÖУ¬ModelÖ÷ÒªÈÏÕæ´¦Öóͷ£Êý¾ÝÂß¼£¬ViewÔòÈÏÕæÏÔʾҳÃ棬¶øControllerÔòÈÏÕæ´¦Öóͷ£Óû§ÇëÇó²¢Å²ÓÃModel»òView¾ÙÐÐÏìÓ¦µÄ´¦Öóͷ£¡£
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
3¡¢ÊµÏÖAJAXÎÞË¢ÐÂÊÖÒյİ취
ÏÂÃ潫ÏÈÈÝÔÚthinkphp¿ò¼ÜÏÂÔõÑùʵÏÖAJAXÎÞË¢ÐÂÊÖÒյİ취£º
°ì·¨1£º½¨ÉèController
Ê×ÏÈÐèÒªÔÚÏîÄ¿Öн¨ÉèÒ»¸öControllerÓÃÓÚ´¦Öóͷ£AJAXÇëÇ󣬲¢ÔÚControllerÖнç˵Êý¾Ý´¦Öóͷ£ºÍÒ³ÃæչʾµÄº¯Êý¡£
ÒÔ¡°Demo¡±ÎªControllerÃû³ÆΪÀý£¬´úÂëÈçÏ£º
<?php namespace app\index\controller; use think\Controller; class Demo extends Controller { public function doSomething() { // Êý¾Ý´¦Öóͷ£´úÂë } public function showSomething() { // Ò³Ãæչʾ´úÂë } }
µÇ¼ºó¸´ÖÆ
°ì·¨2£º±àдAJAXÇëÇó´úÂë
ÔÚÒ³ÃæÖУ¬ÐèҪͨ¹ýJavaScript±àдAJAXÇëÇó´úÂ룬²¢½«ÇëÇó·¢Ë͸øControllerµÄ´¦Öóͷ£º¯Êý¡£
´úÂëÈçÏ£º
<script> function ajaxRequest() { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("content").innerHTML = xhr.responseText; } }; xhr.open("GET", "/index/demo/doSomething", true); xhr.send(); } </script>
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬ÏȽ¨ÉèÁËÒ»¸öXMLHttpRequest¹¤¾ßxhr£¬È»ºó½ç˵ÁËÆä״̬¸Ä±äʱµÄ»Øµ÷º¯Êý¡£µ±xhr.readyState¼´ÊÇ4ÇÒxhr.status¼´ÊÇ200ʱ£¬´ú±íAJAXÇëÇóÀֳɣ¬´Ëʱ´ÓЧÀÍÆ÷·µ»ØµÄÊý¾Ý½«Í¨¹ýJavaScript¶¯Ì¬ÐÞ¸ÄÒ³ÃæÖеÄÄÚÈÝ¡£xhr.open()º¯ÊýÓÃÓÚÖ¸¶¨ÇëÇó·½·¨ºÍÇëÇóµØµã£¬xhr.send()º¯ÊýÓÃÓÚ·¢ËÍÇëÇó¸øЧÀÍÆ÷¾ÙÐд¦Öóͷ£¡£
°ì·¨3£º´¦Öóͷ£ÇëÇó²¢·µ»ØÊý¾Ý
µ±Óû§µã»÷°´Å¥»òÖ´ÐÐijЩ²Ù×÷ʱ£¬»á´¥·¢Ç°ÎÄÖбàдµÄajaxRequest()º¯Êý£¬¸Ãº¯Êý»áŲÓÃControllerÖеÄdoSomething()º¯Êý´¦Öóͷ£ÇëÇó¡£doSomething()º¯ÊýÖ÷ÒªÈÏÕæ´¦Öóͷ£Êý¾ÝÂß¼£¬²¢½«´¦Öóͷ£Ð§¹û·µ»Ø¸øÇ°¶ËÒ³Ãæ¡£
´úÂëʾÀý£º
public function doSomething() { $data = array("name" => "Apple", "price" => "5.00"); return json_encode($data); }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬ÏȽç˵ÁËÒ»¸ö°üÀ¨ÉÌÆ·Ãû³ÆºÍ¼ÛÇ®µÄÊý×é$data£¬È»ºóͨ¹ýjson_encode()º¯Êý½«Êý¾Ýת»»ÎªJSONÃûÌò¢·µ»Ø¡£
°ì·¨4£ºÕ¹Ê¾Êý¾Ý
ÔÚÇ°¶ËÒ³ÃæÖУ¬ÎÒÃÇÐèÒª±àдչʾÊý¾ÝµÄ´úÂë¡£ÕâÀïÎÒÃÇŲÓÃControllerÖеÄshowSomething()À´ÊµÏÖÊý¾Ýչʾ¡£
´úÂëʾÀý£º
public function showSomething() { $this->fetch('example'); }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬Í¨¹ý$this->fetch()º¯ÊýÀ´¼ÓÔØÉúÑÄÔÚ\viewsĿ¼ÏµÄexample.htmlÄ£°åÎļþ£¬ÊµÏÖÁËÊý¾ÝµÄչʾ¡£
4¡¢×ܽá
±¾ÎļòÆÓÏÈÈÝÁËÔÚthinkphp¿ò¼ÜÏÂÔõÑùʵÏÖAJAXÎÞË¢ÐÂÊÖÒÕ¡£Í¨¹ý¶ÔController¡¢ViewºÍJavaScriptµÈµÄ²Ù×÷£¬ÎÒÃÇ¿ÉÒÔÀû±ãµØʵÏÖÎÞˢеÄÒ³Ãæ½»»¥Ð§¹û£¬Ìá¸ßÁËÍøÒ³µÄÏÔʾЧÂʺÍÓû§½»»¥ÐÔ¡£
ÒÔÉϾÍÊÇthinkphp ajaxÊÖÒÕÒ³ÃæÎÞˢеļòÖÊÆÓÏÖµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡