2013-07-09 30 views
3
  • 我正在開發一個javascript模塊,它爲複雜頁面增加了很多 功能。
  • 數據綁定是用php完成的。
  • 我的文件把我的js到我的網頁的結束,所推薦的html5boilerplate

我如何通過從服務器獲取數據到我的js模塊?我唯一能想到的是:將數據存儲在某個DOM變量中,然後從JS文件中讀取數據。像這樣:在javascript文件中使用php數據

PHP:

<script type="text/javascript"> 
    var saveMethodUrl = '<?php echo $this->getUrl("page/save") ?>'; 
</script> 

JS:

module = (function ($) { 
    var url = saveMethodUrl; 
    ... 

但這似乎有點髒。如何做到最好的做法?

+0

Ajax不是這裏的一個選項。 – Sven

+0

好的。那麼你的意思是你不喜歡將數據回顯到腳本標籤中? – iConnor

+0

Ajax是建議方法的次選,因爲它會產生額外的網絡開銷。我傾向於說沒有更乾淨的方式。 –

回答

1

相反,我會在模塊上公開一個方法來設置保存方法URL,然後調用該方法,而不是設置全局變量。

<script type="text/javascript"> 
window.onModuleLoaded = function(module) 
{ 
    module.setSaveMethodURL('<?php echo $this->getUrl("page/save") ?>'); 
} 
</script> 

然後,在你的模塊代碼,你會做類似如下的修改:(取決於設計模式你使用暴露你的模塊)

module = (function ($) { 
var url = saveMethodUrl; 

var setSaveMethodURL = function(save_url) 
{ 
    url = save_url; 

    return url; 
} 

var returnObject = { 
    setSaveMethodURL: setSaveMethodURL 
}; 

//this is executed when the module is loaded via the <script> tag) 
//check to see if the moduleLoaded callback is defined 
if (typeof window.onModuleLoaded != undefined) 
{ 
    //if the moduleLoaded callback is defined and is a function, call it 
    if (typeof window.onModuleLoaded == 'function') 
    { 
     window.onModuleLoaded(returnObject); 
    } 

    //if it's defined and is an object, iterate through the object and call 
    //each function in the object. (this allows you to add multiple callbacks 
    //to be executed when this module is loaded 
    else if (typeof window.onModuleLoaded == 'object') 
    { 
     for (key in window.onModuleLoaded) 
     { 
      if (typeof window.onModuleLoaded[ key ] == 'function') 
      { 
       window.onModuleLoaded[ key ](returnObject); 
      } 
     } 
    } 
} 

//return a reference to your setSaveMethodURL api method 
return returnObject; 

})(); 

至於裝你的模塊異步,你可以看看這個其他stack overflow question about loading javascript asynchronously

+0

爲此,我會必須將我的js模塊從頁面底部放入頭部區域,對不對? – Sven

+0

你不需要,你可以把它放在頁面底部的調用模塊的腳本之前。或者,你可以自己寫一個你的模塊在加載時查找的事件,利用該事件調用setSaveMethodURL API,然後添加你的php代碼來設置變量(通過事件中的api調用)你的頁面,同時仍然在底部加載模塊(甚至如果你想異步) –

+0

異步事件thingy聽起來很棒。您能否通過一些示例代碼讓我意識到正確的方向? – Sven

1

如何調用PHP腳本,返回的JavaScript文件:

<script src="my_js_variables.php"></script> 

而在你my_js_variables.php您有:

<?php 

header('Content-type: text/javascript'); 

$variables = array('saveMethodUrl' => $this->getUrl("page/save")); 

echo "var php = " . json_encode($variables); 

?> 

而且你訪問像php.saveMethodUrl您的JS文件的變量。

實際上這與您提出的解決方案沒有什麼不同,但我認爲它更清潔。

相關問題