javascript - 将国家代码作为 http header 的一部分传递

标签 javascript jquery html http webserver

要求是我需要默认传递访问者国家代码作为 HTTPRequest 的一部分。 我的 common.js 中有以下 jquery 代码

$(function() {

    if (window.sessionStorage) {
        if($('#country').val() == '')
        {
            if(window.sessionStorage.getItem('country') == null)
            {
                if(window.localStorage.getItem('country') == null)
                {
                    $.get("http://ipinfo.io", function(response) {
                        window.sessionStorage.setItem('country', response.country);
                        window.localStorage.setItem('country', response.country);
                    }, "jsonp");
                }
                else
                {
                    window.sessionStorage.setItem('country', window.localStorage.getItem('country'));
                }
            }
            $('#country').val(window.sessionStorage.getItem('country'));
        }       
    }   
});

现在我如何将这个国家代码与默认情况下的每个请求一起传递给网络服务器。我不想将它作为查询参数传递,因为我必须结束修改我所有的 URL,这很痛苦。有任何想法吗?我能以某种方式将它作为 HTTPRequest header 的一部分传递吗?

最佳答案

在此 question 中回答

$.ajaxSetup({
    beforeSend: function (xhr)
    {
       var countryCode = window.sessionStorage.getItem('country');
       xhr.setRequestHeader("CountryCode", countryCode);        
    }
});

关于javascript - 将国家代码作为 http header 的一部分传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33028201/

相关文章:

javascript - 颜色选择器插件脚本导入导致意外标记

javascript - 使用javascript数组时表格内容不显示?

javascript - 如何使用 jQuery 在每个 tr 中选择两个单独的输入?

javascript - 验证输入标签中的最大金额 : (Aurelia)

javascript - jQuery 日期范围之间的天数

javascript - 在 AngularJS 中为 ng-keyup 添加延迟

javascript - svg 元素在 Chrome 中隐藏/显示时重置

javascript - 我需要在页面加载期间添加 throbber 的示例

javascript - 如何动态地将选中的复选框元素添加到 Div 中?

javascript - jQuery:当悬停在主元素上时如何悬停子元素的子元素