Yii客户端脚本在一行中注册脚本

时间:2014-03-15 07:19:20

标签: javascript php yii

我正在使用Yii::app()->clientScript来注册脚本;在php文件中,我用多行编写脚本,但是当它注册到浏览器时,每个脚本文件都会放在一行,包含我的注释,这会产生错误,因为//之后的所有内容都将被称为comment.Script转移之后是这样的:tag.firstChild.onchange=function(){ load_grid(obj); }; } //Comment ....它只有一行。请帮助我。

更新: 这是一个例子:

$cs=Yii::app()->clientScript;           
    $cs->registerScriptFile('//maps.googleapis.com/maps/api/js?sensor=false', CClientScript::POS_HEAD); 

    $cs->registerScript('googlemaps_api','

    function geocode(address, lat_id, lng_id) {
        var geocoder = new google.maps.Geocoder();          

        geocoder.geocode({address: address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {                                      
                $("#"+lat_id).val(results[0].geometry.location.lat());
                $("#"+lng_id).val(results[0].geometry.location.lng());
            } else alert("'.Yii::t('views/config/edit_store_locations_options','ERROR_GEOCODE_ADDRESS').'");        
        });                 
    }
    ', CClientScript::POS_HEAD);    

2 个答案:

答案 0 :(得分:4)

我发现将内联JS代码嵌入到我的registerScript()函数调用非常不方便,并选择成功使用heredoc格式。

$script = <<<EOD

    function geocode(address, lat_id, lng_id) {
        var geocoder = new google.maps.Geocoder();          

        geocoder.geocode({address: address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {                                      
                $("#"+lat_id).val(results[0].geometry.location.lat());
                $("#"+lng_id).val(results[0].geometry.location.lng());
            } else alert("'.Yii::t('views/config/edit_store_locations_options','ERROR_GEOCODE_ADDRESS').'");        
        });                 
    }

EOD;

    Yii::app()->clientScript->registerScript('googlemaps_api', $script, CClientScript::POS_HEAD);

?>

答案 1 :(得分:1)

这是正常的,有些需要的行为。为什么不使用/ ** /来填写你的评论,这样一切都会正常工作。