I'm learning javascript, xml, and html. For a homework assignment, I need to retrieve some data from some nodes of a XML file, concatenate the data, and store the concatenated string in localStorage. I am having trouble in storing the concatenated string in localStorage. I believe the issue is in these two lines -
var s_data = localStorage[students];
$("#clickme").text("Students' first names: " + s_data);
Can someone take a look and give me some tips on how to fix it? Thank you in advance for your help.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<title>HWK</title>
<meta charset="UTF-8">
</head>
<body>
<div id="clickme" onclick="startAjax()">Click me to see all the students' first names</div>
<script>
function startAjax(){
$("#clickme").text("Calling server");
$.ajax({url:"hwk.xml",
success:callbackFunction, error:errorFunction});
}
function callbackFunction(data,info)
{
var students = $(data).find("student first_name");
try {
if (students && students.length)
{
var s_data = localStorage[students];
$("#clickme").text("Students' first names: " + s_data);
}
}
catch (e) {
if (e != window["localStorage"])
alert("No local storage. Should use cookie instead.");
}
}
function errorFunction(data,info){
$("#clickme").text("error occurred:"+info);
}
</script>
</body>
</html>
You can use the setItem() to set a value to the localStorage and getItem() to retrieve it
Ex:
localStorage.setItem('mykey', 'somevalue')
Demo: Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With