首页 文章

使用ajax从localStorage获取数据

提问于
浏览
0

我有一个由一些链接组成的数组,这个数组存储在localStorage中 . 我有一个页面,我想显示所有这些 . 因此,当我将任何项目附加到我的数组时,必须使用ajax将其添加到页面中 .

我有一个函数,只使用本地存储中的数据创建此表:

function get_table(links) {
    let result = ["<table class='table text-center'>"];
    let number = recent.length;

    result.push("<thead><tr><th scope='col'>Page Number</th><th scope='col'>Link</th></tr></thead>")
    result.push("<tbody>")
    for(let link of links) {
        result.push(`<tr><td>${number}</td><td>${link}</td></tr>`);
        number--;
    }
    result.push("</tbody></table>");
    return result.join('\n');
  }

但我不知道在哪里应用ajax . 我试过这样做:

$.ajax({
      type: "POST",
      url: "http://127.0.0.1:8000",
      data: {recent: localStorage.getItem('RecentPages')},
      dataType: 'json',
      success: function(data)
      {
          $('.container').append(get_table(data));

      },
  });

但它不起作用 . 我怎样才能实现目标?

1 回答

  • 0

    有一种方法可以将新数据添加到表中而无需重新编写 . 我正在寻找一个回调或事件,当 Array.push 发生但没有 .

    function ArrayEvent(array){
    this.Array = array;
    this.push = function(data){
        //push the data in the array
        this.Array.push(data);
    
        //store it in the local storage
        localStorage.setItem("links", JSON.stringify(this.Array));
    
        //add to the end of the table
        $("table.table > tbody").append(`<tr><td>${data.number}</td><td>${data.link}</td></tr>`);
    };
    

    }

    如果你不喜欢它,你也可以试试 Proxyhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

相关问题