Javascript:如何在ajax成功后每次更改localStorage Key的值

时间:2016-08-07 05:58:41

标签: javascript jquery ajax html5

我目前正在努力解决这个问题,我的localstorage键值在ajax成功时不会更新值并保留旧的存储数据,但只有当我按f5或刷新不友好的页面时它才会更新。

var hide_cat = $('#hide_cat').val();
function fetch_data(){
$.ajax({
    url: '../ajax/ajax_fetch_loop.php',
    data : {hide_cat : hide_cat},
    type: 'post',
    cache: false,
    success:function(data){
        localStorage.setItem('dat', data); /*<-- this  one should update new                        
                                                 value every time success,   
                                                 however its not working, it 
                                                 remians the old data and i 
                                                 need to refresh before it 
                                                 store a new value*/
    }
});
}
fetch_data();

function fetch_datas(){

//so after update i should get a new value after ajax success
var table_data = localStorage.getItem('dat');
$('#tboy_labasmo').html(table_data);
}
fetch_datas();  

1 个答案:

答案 0 :(得分:0)

您需要在存储回复之前使用JSON.stringify

localStorage.setItem("dat", JSON.stringify(data));