2013-07-16 41 views
1

我有一些關於開發和生產的網站,它們被諸如localhost/demo1 localhost/demo2..demo3等文件夾隔開。在JS中處理生產和開發的路徑/鏈接

問題是我的JS。每次我部署它們,我都必須更改一些JS文件的路徑,特別是那些使用AJAX的路徑。

假設下面的代碼是jQuery中的ajax的URL參數:

//on dev: 
url: '/demo1/some-action.php' 

//on prod: 
url: '/some-action.php' 

你是如何處理這對JS?

回答

2

你可以聲明取決於調用頁面的位置的文件夾路徑 像

function sitePath(){ 
    if(this.result!=undefined){ 
     // we have already tested so return the stored value 
     return this.result 
    } 
    var folders=window.location.pathname.split('/'); 
    if(folders.length && folders[0].indexOf('demo')==0){ 
     // we are inside a demo folder so return and store the demo folder name 
     return this.result='/' + folders[0]; 
    }else{ 
     // we are in the production environment so store an empty string 
     return this.result = ''; 
    } 
} 

返回一個函數,那麼在你的代碼中使用:

url: sitePath()+'/some-action.php' 
+0

kevmc,對不起最近,我檢查了這個,並忘記給你正確的答案。 – rffaguiar

+0

我認爲它應該是'folders [1]'。對我來說,'folders = [「」,「demo」,...]'。 – shimizu