代码之家  ›  专栏  ›  技术社区  ›  espresso_coffee

如何按ID/键从sessionstorage访问记录?

  •  1
  • espresso_coffee  · 技术社区  · 6 年前

    我有保存在sessionstorage中的数据,下面是我在sessionstorage中保存数据的示例。

    $.ajax({
        type: 'POST',
        url: 'Components/Functions.cfc?method='+cfMethod,
        data: formData,
        dataType: 'json'
    }).done(function(obj){
        sessionStorage.setItem('Books',JSON.stringify(obj.DATA));
    }).fail(function(jqXHR, textStatus, errorThrown){
        alert('Error: '+errorThrown);
    });
    

    在sessionstorage中保存记录后,它们看起来如下:

    {
      "14": {
        "COMMENTS": "",
        "RECORDID": 14,
        "NAME": "Decorah Sector",
        "AGENCY": "01",
        "CODE": "011A"
      },
      "15": {
        "COMMENTS": "",
        "RECORDID": 15,
        "NAME": "Waukon Field",
        "AGENCY": "01",
        "CODE": "011B"
      },
      "16": {
        "COMMENTS": "Test 524",
        "RECORDID": 16,
        "NAME": "New Hampton",
        "AGENCY": "01",
        "CODE": "011C"
      }
    }
    

    正如您所看到的,每个记录都有唯一的键,一旦用户决定编辑记录,我所要做的就是从sessionstorage中提取数据并传递 id 这是匹配的唯一键。以下是我的编辑功能示例:

    function editBook() {
        var recordID = $(this).closest('tr').attr('id'), // This id will be retrieved from presentation table. Each row has unique id that match sessonStorage.Books records.
            bookRecord = JSON.parse(sessionStorage.Books[recordID]);
            console.log(bookRecord); //For testing purpose.
        if(bookRecord){
            $.each(regionRecord, function(name, value){
                var elementName = $('[name="'+'frmSave_'+name.toLowerCase()+'"]'),
                    elementType = elementName.prop('type'),
                    elementVal = $.trim(value);
    
                switch(elementType){
                    case 'select-one':
                        elementName.val(elementVal);
                        break;
                    case 'textarea':
                        elementName.val(elementVal);
                        break;
                    default:
                        elementName.val(elementVal);
                }
            });
        }
    }
    

    因为某种原因在我之后 console.log() 我没有得到具体的数据 身份证件 我在会议上通过的。我不确定我的语法是否正确,或者是否有其他问题。我遵循与JS对象基于唯一键访问记录相同的步骤。如果有人看到我的代码中的问题在哪里,请告诉我。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Barmar    6 年前

    对象是 JSON.parse() ,您需要将索引放在那里。

    bookRecord = JSON.parse(sessionStorage.Books)[recordID];
    
        2
  •  1
  •   msanford    6 年前

    这条线

    bookRecord = JSON.parse(sessionStorage.Books[recordID]);
    

    应该是

    bookRecord = JSON.parse(sessionStorage.Books)[recordID];
    

    因为您想要访问从JSON解析的对象的记录。