【问题标题】:Dealing with Paths/Links on Production and Development in JS在 JS 中处理生产和开发的路径/链接
【发布时间】:2013-07-14 00:11:47
【问题描述】:

我有一些关于开发和生产的网站,由以下文件夹分隔:localhost/demo1 localhost/demo2..demo3 等等。

问题是我的 JS。每次我部署它们时,我都必须更改 JS 文件的一些路径,尤其是那些使用 AJAX 的路径。

假设下面的代码是jquery ajax中的url参数:

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

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

你如何在 JS 上处理这个问题?

【问题讨论】:

    标签: javascript path relative-path web-deployment


    【解决方案1】:

    您可以声明一个函数,该函数根据调用页面的位置返回文件夹路径 像

    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'
    

    【讨论】:

    • kevmc,抱歉来晚了,我检查了这个,忘记给你正确答案了。
    • 我认为应该是folders[1]。对我来说,folders = ["","demo",...].
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2021-08-30
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    相关资源
    最近更新 更多