CakePHPã§jQueryããã®ã¾ã¾æ¸ãéã«ä½¿ãããã¹è£å®ã¡ã½ãããjQueryãªãã¸ã§ã¯ãã«è¿½å ããã
CakePHPã§ã¯HtmlHelper::script()ã使ãJavaScriptãã¡ã¤ã«ãèªã¿è¾¼ãscriptã¿ã°ãçæãã¾ããããã¯ããã§ä½¿ããã§ãããjQueryãã©ã°ã¤ã³ã使ãå ´åã¯ããã¼ãå®äºã®ã³ã¼ã«ããã¯ã§åããããã¨ããã§ããã¾ããå é¨ã«ç½®ãã¦ããJSONã¨ãç»åã¨ããèªã¿è¾¼ãã§ãã³ã¼ã«ããã¯ã§å¦çãããããªå ´åã«ããã¹ã®æ¸ãæ¹ã§å°ãã¾ããããªã®ã§jQueryãªãã¸ã§ã¯ãã«ã²ã¨ã¤ãã¡ã½ããã追å æ¡å¼µãããã«ãã¼ã¡ã½ãããä½ã£ã¦ã¿ã¾ããã
ãªããCakePHPã¯1.3ç³»ããJsHelperã§ãPrototype.jsã ãã ã£ãã®ãjQueryã«ã対å¿ãã¾ããããã©ãCookbookããã£ã¨çºããç¨åº¦ã ã¨ãjQueryã§åºæ¥ãäºã®ä¸é¨ãphpã§æ¸ããããã«ããã ãã®æ§ã«æãã¾ããjQueryã«æ £ãã¦ããªãããããæ¸ãæ¹ãéãã ãã§ããã©ãããã ãã®æ§ã«è¦ãã¾ããããããªè¨³ã§ãJsHelperã¯ä½¿ã£ããã¨ãã¾ã ç¡ãã§ããã¾ããjQueryã使ã£ã¦ãäºåæã¨ãªãã¾ãã
<?php $this->Html->script('jquery.example'); ?>
HtmlHelper::script()ã使ã£ã¦jQueryãã©ã°ã¤ã³ãèªã¿è¾¼ããªããåç´ã«ãããªãã¾ããããã¯ããã§è¯ããã§ããã©ããã¼ãå®äºæã®ã³ã¼ã«ããã¯ã¨ããã®ãæ¸ãã¾ããã
åºæ¥ãäº
$(function(){ $.getScript($.webroot('js/jquery.example.js'), function(){ $('#foo').exampleMethod(); }); });
$.getJSON($.webroot('data/foo.json'), {}, function(data, status){ $.each(data.results, function(i, item){ console.log(item.text); }); });
ãããªæãã§ãwebrootã®ãã¹ä»¥ä¸ããæ¸ããã¨ãåºæ¥ã¾ããHtmlHelper::script()ã¨éã£ã¦jsãã©ã«ãããæ¸ããªãã¨ã§ããã©ãéçºç°å¢ãªã©ã§ããã£ã¬ã¯ããªåã£ã¦åããã¦ãã¦ãããã®ã¢ããªã®webrootã®ãã¹ã¾ã§è£å®ãã¦ããã¾ããã¾ãããããã³ã¼ã«ããã¯ã«ããªãã£ã¦ããheadã¿ã°å
ã§ãã©ã°ã¤ã³ãèªãããã«æ¸ãã¨ãã°ã$(document).ready()
æã«ã¯ã»ã¼ç¢ºå®ã«ãã¼ãã§ãã¦ãã¨ã¯æãã¾ããã©ãJSONã¨ãã®å ´åã¯ä¾¿å©ã«ãªãããããªããã¨ã
$.getJSON('<?php echo Router::url(); ?>data/foo.json', {}, function(data, status){ $.each(data.results, function(i, item){ console.log(item.text); }); });
å
ã
Router::url()
ã使ãã°åºæ¥ããã§ãããJavaScriptã®ã³ã¼ãä¸ã«phpã¿ã°ã¨ãã¨ã¦ãè¦ã¥ããã§ãããªãå
¨é¨javascriptã«ãã¦ãã¾ããã¨ãããã®ã§ãã
äºåæºå
<?php echo $this->Html->script('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'); echo $this->ExHtml->setWebroot(); //jQueryãèªãã å¾ã«å¼ã¶
ã³ã¼ã
<?php /** * Extended HtmlHelper * @author kanonji */ class ExHtmlHelper extends HtmlHelper { /** * $.webroot() for jQuery * * To get webroot path when using jQuery. * This is a little closer to Helper::webroot(). * * $.getScript($.webroot('js/jquery.example-plugin.js'), function(){//callback}); * * @param array $options */ public function setWebroot($options = array()){ $url = $this->url('/'); return $this->scriptBlock(" $.extend({ webroot: function(path) { if(! path) path = ''; return '{$url}'+path; } });" , $options); } }ex_html.php · GitHub
https://gist.github.com/798322/7de6b301f10efafdd658b90bba376f35fd5e8738
ã³ã¼ãã«ééãããã£ãã®ã§ä¿®æ£ãã¾ããã@nojimage ãããããã¨ããããã¾ãã