如果语言更改,请更改缓存

本文关键字:缓存 如果 语言 | 更新日期: 2023-09-27 18:02:51

我有一个填充菜单的方法,它是这样的:

function MenuPopulate(url, listname, target) {
    var lang = "Espanol";
    if ((window.location.href.indexOf("lang=en") > 0)) {
        lang = "English";
    } 

       $(function () {
                    $.ajax({                       
                        url: "https://myapi.company.com/api/myapi/getmenu?idioma=" + lang ,
                         async: false,
                        type: 'GET',
                        dataType: "json",
                        success: function (data) {
                           console.log(data);
                           completeMenu(data, target)
                           //localStorage.setItem('data', JSON.stringify(data))                                                   
                           },
                        error: function (response) {
                          failureMenu(response, target)
                        }
                    });
                });
}    
function completeMenu(data, target) {
    var prefix = "<ul class='nav navbar-nav navbar-right'>";
    var sufix = "</ul>";
    var items = data;
    var menu = "";
    for (item in items) {
        if(items[item].Titile == "JOIN US"  ){
       menu += "<li><a href='#mymodal' data-toggle='modal' data-target='#mymodal'>" + items[item].Titile + "</a></li><li class='divider-vertical'></li>"
        }
        else if(items[item].Titile == "CONTACT US"){
        menu += "<li><a href='#mymodal2' data-toggle='modal' data-target='#mymodal2'>" + items[item].Titile + "</a></li><li class='divider-vertical'></li>"
        }
        else{
            menu += "<li><a href=" + items[item].Enlace + ">" + items[item].Titile + "</a></li><li class='divider-vertical'></li>";
        }
    }
    $(target).html(prefix + menu + sufix);
}
function failureMenu(data, target) {
    console.log(data);
    $(target).text("Ocurrió un error en la carga del menú. Por favor revise la consola para más información");
}

它运行得很好,除了加载页面的时间,所以现在我用localStorage将方法存储在缓存中,所以我做了这个类:

$(document).ready(function() {

    GetGlobal();
});
    function GetGlobal() {

        var lang = "Espanol";
        if ((window.location.href.indexOf("lang=en") > 0)) {
            lang = "English";
        } 
        var page = window.location.pathname.replace("/SitePages/", "");
        if (localStorage.getItem("Menu") == null) {
            $.ajax({
                url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
                async: false,
                type: 'GET',
                dataType: "json",
                success: function(data) {
                    CompleteGlobal(data);
                    //alert("Cargo con exito");
                },
                error: function(data) {
                    //failureGlobal(data);
                    alert("No cargo");
                }
            })
        } else {
          //  alert("la cookie esta cargada");
             CargaGlobal();
            //localStorage.getItem("Menu")
        }
    }

    function CargaMenu() {
        $.ajax({
            url: "https://myapi.company.com/api/myapi/getmenu?idioma=" + lang,
            async: false,
            cache:true,
            type: 'GET',
            dataType: "json",
            success: function(data) {
                console.log(data);
                completeMenu(data, target)
            },
            error: function(response) {
                failureMenu(response, target)
            }
        });
    }

    function CompleteGlobal(data) {
        data.Menu //lista de menus
        data.Pie // lista pie de pagina
        data.Mapa
        data.Ligas
        localStorage.setItem("Menu", JSON.stringify(data.Menu));
        localStorage.setItem("Pie", JSON.stringify(data.Pie));
        localStorage.setItem("Mapa", JSON.stringify(data.Mapa));
        localStorage.setItem("Ligas", JSON.stringify(data.Ligas));
        localStorage.setItem("Enlace", JSON.stringify(data.Enlace));

        CargaGlobal();

    }

    function CargaGlobal() {
        completeMenu(JSON.parse(localStorage.getItem("Menu")), "#BarraNavegacion");
        completeSiteMap(JSON.parse(localStorage.getItem("Mapa")), "#MapaSitio");
         completeImgLinks(JSON.parse(localStorage.getItem("Enlace")), "#EnlacesImagen");
         completeFooter(JSON.parse(localStorage.getItem("Pie")), "#Footer");


    }


    function completeBanner3(target) {
        var items = localStorage.getItem("Menu");
        var menu = "";
        for (var item in items) {
            menu += "<div class='col-md-4 text-center'><div><a href='" + items[item].Enlace + "'><img src='" + items[item].Imagen + "' class='img-responsive img-center' /></a></div><div class='t02 text-center'>" + items[item].Titulo + "</div><div class='t03 text-center'>" + items[item].Descripcion + "</div></div>";
        }
        $(target).html(menu);
    }

但是当我改变我的网站的语言它只是不加载其他语言的菜单,我想再次加载cookie如果语言是不同的"西班牙语"所以我想我可以做一些像

  if (localStorage.getItem("Menu") == null && lang == "Espanol") {
                $.ajax({
                    url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
                    async: false,
                    type: 'GET',
                    dataType: "json",
                    success: function(data) {
                        CompleteGlobal(data);
                        //alert("Cargo con exito");
                    }else if(localStorage.getItem("Menu") == null && lang == "English"){
         $.ajax({
                    url:  "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
                    async: false,
                    type: 'GET',
                    dataType: "json",
                    success: function(data) {
                        CompleteGlobal(data);
},
                    error: function(data) {
                        alert("No cargo");
                    }
                })
            } else {
                 CargaGlobal();
            }
        }

但是它不工作,你知道在这种情况下我需要做什么吗?关于

如果语言更改,请更改缓存

与其将单个部件保存到localStorage中,有时使用JSON.parseJSON.stringify来获取对象更容易。

这是一个相当长的例子,但我注释了很多,试图使它更容易理解。这是一个不同概念的说明,所以它不能完全解决你的问题,但我相信它会让你更接近一个解决方案。

EDIT: StackOverflow脚本运行器不喜欢localStorage。下面是一个JSFiddle,看看它是如何工作的:https://jsfiddle.net/subterrane/9prr5ks6/

编辑,编辑:另外,我不会说西班牙语,所以怪谷歌翻译愚蠢的菜单按钮标签。

var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
  lang = "English";
}
// function to getMenuData
function getMenuData() {
  // get the saved data from localStorage
  var menuData = JSON.parse(localStorage.getItem('menuData'));
  // if it doesn't exist, or if our language is missing, fetch the data from the server
  if (menuData == null || menuData[lang] == null) {
    // this is a stub function. Pretend it's doing an ajax request
    // the second argument here is a callback function. It would be
    // the ajax success function.
    fetchMenuData(lang, function(data) {
      // if we did have some of the data, use it, or start with an empty object
      menuData = menuData || {};
      // set the server response to the menuData object
      menuData[lang] = data;
      // stringify the object and stash it in localStorage
      localStorage.setItem('menuData', JSON.stringify(menuData));
      // display the menu
      displayMenu(menuData);
    });
  } else {
    // we go the data from the cache, so display the menu
    displayMenu(menuData);
  }
}
// this is a fake function that pretends to get menuData from a server
function fetchMenuData(lang, callback) {
  // wait 2 seconds, then call the response function
  setTimeout(response, 2000);
  // response function sends some data back to the callback depending on the requested language
  function response() {
    callback(lang == "Espanol" ? [{
      name: 'Casa',
      link: 'something.html'
    }, {
      name: 'Lejos',
      link: 'somethingelse.html'
    }] : [{
      name: 'Home',
      link: 'something.html'
    }, {
      name: 'Away',
      link: 'somethingelse.html'
    }]);
  }
}
// function to display the menu
function displayMenu(data) {
  // update the text in some of the buttons
  document.getElementById('home').innerHTML = data[lang][0].name;
  document.getElementById('away').innerHTML = data[lang][1].name;
  // looks kinda funny, but this just puts the opposite of the current language
  // on the button to make it feel like a toggle button
  document.getElementById('toggle').innerHTML = lang == "Espanol" ? "English" : "Espanol";
  // show the menu now that it's filled in
  document.getElementById('menu').classList.remove('hide');
}
// set up a click handler on the language toggle button
document.getElementById('toggle').addEventListener('click', function() {
  // hide the menu while we mess with it. Could take a while to get the menu
  // data back from our 'server'
  document.getElementById('menu').classList.add('hide');
  // set the language to the opposite of whatever it was before
  lang = lang == "Espanol" ? "English" : "Espanol";
  // get the menu data from the cache or server
  getMenuData();
});
// kick it all off by getting the menu data from the server
getMenuData();
.hide {
  display: none;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<div class="container">
  <div id="menu" class="hide">
    <button id="home"></button>
    <button id="away"></button>
    <button id="toggle"></button>
  </div>
</div>
相关文章: