Javascript函数根据URL加载不同的config.json文件


Javascript function to load different config.json files depending on URL

我有一个移动网站,它使用以下javascipt加载config.json文件:

$.ajax({
        type:'GET',
        url: '/config.json',
        contentType: 'plain/text; charset=UTF-8',
        dataType: 'json',
        success: function(data){
        },
        error: function(jqXHR, textStatus, errorThrown){
        },
        complete: function(jqXHR, textStatus){
            initConfig($.parseJSON(jqXHR.responseText));
        }
    });

我希望能够根据环境加载不同的 config.json 文件。 例如,qa.site.com、staging.site.com 和 www.site.com。 目前,javascript只加载一个文件,其内容只能是 qa.site.com,staging.site.com 或 www.site.com。 如何修改此现有代码以适用于所有三个环境?

function getConfigFile() {
    switch (window.location.host.split(':')[0]) {
        case 'qa.site.com':
            return 'config-1.json';
        case 'www.site.com':
        case 'site.com': // optional, remove if incorrect
            return 'config-2.json';
        default:
            return 'config-default.json';
    }
}
$.ajax({
   // ...
   url: getConfigFile(),
   // ...
});

在玩够了之后,我找到了答案:

// Check URL address and set appropriate config.json file 
    var whichjson = (window.location.host);
    var configurl = '';
    function getConfigFile(configurl) {
    switch (whichjson) {
        case 'qa.site.com':
            var configurl = '/config-qa.json';
            return configurl;
            break;
        case 'staging.site.com':
            var configurl = '/config-stg.json';
            return configurl;
            break;
        default:
            var configurl = '/config-default.json';
            return configurl;
            break;
         }
    }
    // _request('/config.json', 'getLocalData', 'POST', '/', initConfig, false);
    $.ajax({
        type:'GET',
        url: getConfigFile(),
        contentType: 'plain/text; charset=UTF-8',
        dataType: 'json',
        success: function(data){
        },
        error: function(jqXHR, textStatus, errorThrown){
        },
        complete: function(jqXHR, textStatus){
            initConfig($.parseJSON(jqXHR.responseText));
        }
    }
    );