Javascript 以向导形式清除本地存储时出现问题

Javascript 以向导形式清除本地存储时出现问题,javascript,jquery,Javascript,Jquery,我正在使用步骤向导表单和以下代码 $(document).ready(function(){ localStorage.removeItem('dateFormat'); readcategories(); ... ... }); function getDateFormatFromDatabase() { $.ajax({ url: 'index.php?action=getDateFormat', type:

我正在使用步骤向导表单和以下代码

$(document).ready(function(){
    localStorage.removeItem('dateFormat');
    readcategories();
    ...
    ...
    });

function getDateFormatFromDatabase() {
    $.ajax({
        url: 'index.php?action=getDateFormat',
        type: 'POST',
        dataType: 'JSON',
        success: function(data)
        {
            dateFormat = data.dateFormat;
            localStorage['dateFormat'] = dateFormat;
        }
    });
}

function getDateFormat() {
    getDateFormatFromDatabase();
    var dateFormat = localStorage['dateFormat'];
    //  alert(dateFormat);
    return dateFormat;
}

function checkValidDate(dateValue) {
    var dateFormat = getDateFormat();
    ...
    ...
}


..... wizard form code
.....

onFinishing: function (event, currentIndex) {
    var form = $(this);

    var purchasedate = $("#purchasedate").val().trim();
    var purchasedate = new Date(purchasedate);
    if(checkValidDate(purchasedate.toDateString()) == false)
    {
        displayDateErrorMessage("Purchase Date");
        return false;
    }
    ...
}
我正在清除
document.ready
函数中的
localStorage
,因为我希望它始终包含从函数
getDateFormat
中的数据库中获取的新值。现在它总是清除
日期格式
,结果总是得到未定义的值,并且日期未验证


请帮忙

首先:

而不是使用:

localStorage['dateFormat'] = dateFormat;

你需要:

localStorage.setItem('dateFormat', dateFormat);

阅读有关本地存储的更多信息


秒:

函数
getDateFormatFromDatabase()包含一个ajax调用。由于ajax调用是一个异步操作,这意味着您在调用
getDateFormatFromDatabase()后将不会将
dateFormat
设置为
localStorage
。要解决这个问题,您需要通过设置
async:false
使其同步:

function getDateFormatFromDatabase(callback) {
    $.ajax({
        url: 'index.php?action=getDateFormat',
        type: 'POST',
        async: false,
        dataType: 'JSON',
        success: function(data)
        {
            localStorage.setItem('dateFormat', data.dateFormat);
        }
    });
}

它总是以空值返回,并且如果我删除行localStorage.removietem('dateFormat');它的工作原理是:我应该保留localStorage.removietem('dateFormat');或者不在ready Function上,您可以删除它。它在主线程上抛出同步XMLHttpRequest已被弃用,因为它会对最终用户在控制台中的体验产生有害影响
var dateFormat = localStorage.getItem('dateFormat');
function getDateFormatFromDatabase(callback) {
    $.ajax({
        url: 'index.php?action=getDateFormat',
        type: 'POST',
        async: false,
        dataType: 'JSON',
        success: function(data)
        {
            localStorage.setItem('dateFormat', data.dateFormat);
        }
    });
}