Unable to store the list item value using session storage in Sharepoint 2016
-
21-02-2021 - |
Frage
I click on a link then it's updating the count column value in the list. But after reloading the site, the count column value becomes 0 in the list. I am updating the count value using count variable and included that variable in rest api data to increment the count to that list item. So, I have tried my best including session storage property in the code but it again becomes 0 after reloading the site. Please help and correct me if I have done any mistake in the code.
var count = 0;
function updateItems() {
count = count + 1;
var resturl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('demo')/getItemById(1)";
var itemType = GetItemTypeForListName('demo');
$.ajax({
url: resturl,
type: "POST",
data: JSON.stringify({'__metadata': { 'type': itemType }, 'Count': count }),
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"IF-MATCH":"*"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('List Item Updated');
}
function onError(error) {
alert(JSON.stringify(error));
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
}
function storeCount(count) {
if(typeof(Storage) !== "undefined") {
if (sessionStorage.count) {
sessionStorage.count = Number(sessionStorage.count)+1;
} else {
sessionStorage.count = 1;
}
}
}
Lösung
Try to modify the code as this, use sessionStorage.setItem to save count into sessionStorage:
<script type="text/javascript">
function updateItems() {
if (typeof (Storage) !== "undefined")
{
if (sessionStorage.count) {
sessionStorage.setItem('count',Number(sessionStorage.count) + 1);
} else {
sessionStorage.setItem('count',1);
}
}
var resturl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('demo')/getItemById(1)";
var itemType = GetItemTypeForListName('demo');
$.ajax({
url: resturl,
type: "POST",
data: JSON.stringify({ '__metadata': { 'type': itemType }, 'Count': sessionStorage.count }),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"IF-MATCH": "*"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('List Item Updated');
}
function onError(error) {
alert(JSON.stringify(error));
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
}
</script>
<input type="button" onclick="updateItems()" value="Test"/>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit sharepoint.stackexchange