//编辑
感谢目前为止所有的帮助。我担心,我做错了,所以我重新构造了整个代码,也是localStorage Array的“结构”
这是我的完整代码及其背后的意图。我想检查连接(我使用pingjs.js),如果没有连接,用户输入将存储在localStorage中。如果我们回来ping,我们通过jQuery AJAX上传localStorage中的所有内容,并从localStorage Array中删除这些提交的数据(例如,不是之后的所有内容)。问题是,我想避免重复(更新已经存在的基于stnr AND pstn的数据),并且还获得类似于索引localStorage数组的唯一ID。
到目前为止,这是我的代码,除了indizes和已经存在的stnr AND pstn的更新:
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/pingjs.js"></script>
<script>
$(document).ready(function() {
$('#store').click(function() {
var startnummer = $("#startnummer").val();
var ergebnis = $("#ergebnis").val();
var position = $("#position").val();
var data = [
{
"stnr": startnummer,
"rslt": ergebnis,
"pstn": position
}
]
/*
So far I use localStorage.length for indexing, but
I want something for checking of duplicates and update
them if necessary, based on stnr AND pstn, so if these
are same, only update rslt
*/
localStorage.setItem((localStorage.length), JSON.stringify(data));
});
// We got a ping
ping('https://example.com/').then(function(delta) {
if(window.localStorage !== undefined) {
var fields = $(this).serialize();
$.ajax({
type: 'POST',
url: 'xyz.php',
data: fields,
success: function(html){
// Here I want to delete all the passed data
localStorage.removeItem( ??? );
// Output status
$('#status').fadeIn(500).delay(5000).fadeOut(500).html(html);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
// We have no ping
}).catch(function(err) {
alert('Could not ping remote URL', err);
});
});
</script>
存储工作没有问题。所以这里没问题。
您似乎可能完全不了解localStorage API。我建议从MDN阅读localStorage
。
第一个问题是,您可能错误地将信息存储在localStorage中。本地存储是基于密钥的。这意味着所有数据都通过密钥位于本地存储中。例如{"key" : "data"}
。
附注,本地存储中的数据保存为字符串。所以为了read/write
数据to/from
本地存储你需要stringify/parse
它。
为了继续你的问题,我的印象是你将整个数组保存在localStorage中,然后尝试删除数组内的每个键。如前所述,由于一些原因,这不会起作用。首先,您不能使用localStorage.removeItem()
方法删除存储的对象,因为该对象实际上是一个字符串而未被解析。其次,即使它没有保存为字符串,该功能也不会对存储数据进行操作,而是对存储数据的密钥进行操作。你的代码遗漏了什么,这将有助于你在localStorage
首先保存的方式。因为在这种情况下你甚至不需要三次调用removeItem()
,只需在它所有存储的密钥上调用一次。让我举一个例子,我认为可能与你的问题有关:
var data = [
{
"id": 1,
"name" : "Joe"
},
{
"id": 2,
"name": "Peter"
}
]
//Setting the data to localStorage under the key "people"
localStorage.setItem("people", data);
// ... inside your ajax function
...({
//Remove whole array of data based on key
localStorage.removeItem("people");
//All done with removal
//Rest of your code
})
如果您希望删除localStorage
中的那些特定键,您将要么必须单独保存它们(推荐),要么您将不得不每次都读取,解析,编辑,重新保存(不推荐)数据你想要那样做的时间。
调用removeItem
函数传递要删除的数据的键。
$.ajax({
type: 'POST',
url: 'xyz.php',
data: {
results: resultobj
},
success: function(callback){
// Delete data from staticLS here
localStorage.removeItem("tmemberData")
// Output message of callback status
$('#status').fadeIn(500).delay(5000).fadeOut(500).html(callback);
}
});