2013-07-16 42 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