Here is the code of the send.html file:
<ul id="ul-list">
<li><input type="text" class="input-text"><input type="text" class="input-text"></li>
<li><input type="text" class="input-text"><input type="text" class="input-text"></li>
<li><input type="text" class="input-text"><input type="text" class="input-text"></li>
<li><input type="text" class="input-text"><input type="text" class="input-text"></li>
</ul>
<button type="button">Send</button>
This is the JQuery code when user clicks the button.
$("button").click(function(){
var data = html2json();
storeUserDataInSession(data);
window.location = 'slider.html';
});
data variable contains the string value that is return by the html2json() function.
Here is the functionality of the html2json() function for getting the text from the input boxes and creating a JSON string.
function html2json() {
var key=['Terms','Definitions'] ;
var c =0;
var json = '{"UserData":[';
var otArr = [];
var tbl2 = $('#ul-list li').each(function(i) {
x = $(this).find('.input-text');
var itArr = [];
x.each(function() {
itArr.push( '"'+key[c]+'":'+'"' + $(this).text().trim() + '"');
c++;
});
y.each(function() {
itArr.push( '"'+key[c]+'":'+'"' + $(this).attr('src') + '"');
});
otArr.push('{' + itArr.join(',') + '}');
c =0;
})
json += otArr.join(",") + ']}';
return json;
}
After getting the value JSON string, storeUserDataInSession() is called in which i have passed the JSON string as a parameter.
function storeUserDataInSession(userData) {
var userObjectString = JSON.stringify(userData);
window.sessionStorage.setItem('userObject',userData);
}
The JSON.stringyfy() function create a JSON string out of an object/array.
After that i have stored the JSON data into the session and given the name "userObject".
In order to retrieve this data in receive.html page, the following JS code is as follows:
$(document ).ready(function() {
var data = {
getUserDataFromSession: function() {
var userData = window.sessionStorage.getItem('userObject');
console.log(userData);
return JSON.parse(userData);
}
}
var userDataObject=data.getUserDataFromSession();
for(i = 0; i < userDataObject.UserData.length; i++) {
$('div').append('<p><span>'+userDataObject.UserData[i].Terms+' : </span><span>'+userDataObject.UserData[i].Definitions+'</span></p>')
}
});
In the data variable i am getting the data from the session by providing the session name i.e., "userObject". now this data is in a JSON string format. In order to convert this data into JSON object i have passed this data into JSON.parse() function.
This value is passed to userDataObject variable.
Now to access the value, iteration is done till the length of the JSON object and values are accessed by the key-value pair.
0 Comment(s)