简体   繁体   中英

LocalStorage value problem at refresh page

I have a problem with some currencies in JavaScript, AJAX. Everything works perfectly, as long as the page is not refreshed. I need that the html (select, span) to be synchronized with the localstorage.

So at the time of refreshing the page, all data remains as local storage - not in the dom element.

Here is code

 /*========= CAMBIO DE DIVISA ==========*/ divisas(); function divisas() { $("#cambiarDivisa").append('<option value="USD">$ USD</option>'+'<option value="MXN">$ MXN</option>'+'<option value="EUR">€ EUR</option>') } /*========= CAMBIO DE DIVISA ==========*/ $("#cambiarDivisa").change(function(){ var divisaBase = "USD"; var divisa = $(this).val(); $.ajax({ url: "https://free.currconv.com/api/v7/convert?q="+divisaBase+"_"+divisa+"&compact=ultra&apiKey=MYAPIKEY", type:"GET", cache: true, contentType: false, processData: false, dataType:"jsonp", success:function(respuesta){ var divisaString = JSON.stringify(respuesta); var conversion = divisaString.substr(11,6); localStorage.setItem("respuesta", JSON.stringify(divisaString)); var respuestadivisa = JSON.parse(localStorage.getItem("respuesta")); var divisavalue = respuestadivisa.substr(6,3); console.log("respuesta",divisavalue); $(".cambioDivisa").html(divisavalue); } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="cambioDivisa">USD</span> <div class="divisa"> <select class="align-self-end" name="divisa" id="cambiarDivisa" </select> </div> 

You should load the values back to the Options element at the startup of your web page. So, instead of putting the data loading inside ajax callback itself, put it in $(document).ready .

$(document).ready(function() {

    var respuestadivisa = JSON.parse(localStorage.getItem("respuesta"));
    var divisavalue = respuestadivisa.substr(6,3);

    console.log("respuesta",divisavalue);

    $(".cambioDivisa").html(divisavalue);

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM