#json #ajax #charts #local-storage
Вопрос:
Я вообще не могу заставить работать функцию graph (). Я попытался изменить свой код в меру своего понимания и исследовал несколько тем по этой проблеме, но я не могу ее получить. Мне нужно отобразить данные, хранящиеся в локальном хранилище, с помощью JSON. Я пытаюсь использовать canvas для построения графика на основе данных, извлеченных из .getJSON. Я новичок в кодировании и не могу понять, что я делаю не так. Я чувствую, что данные из локального хранилища не попадают в график функций(). Но я не уверен, как его туда доставить. Помощь была бы очень признательна.
$( "#btnEnter" ) .click(function() {
var password=getPassword();
if(document.getElementById("passcode").value==password){
$("#btnEnter").attr("href","menu_Page.html").button();
}
else {
alert("Incorrect password. Please enter a valid password.");
}
});
/*Used in index.html*/
function getPassword() {
if (typeof(Storage) == "undefined") {
alert("Your browser does not support HTML5 localStorage. Try upgrading.");
}
else if(localStorage.getItem("user") !=null) {
return JSON.parse(localStorage.getItem("user")).NewPassword;
}
else {
/*Default password*/
return "707";
}
}
/*Used in index.html*/
function checkPassword() {
if (document.getElementById("passcode").value == getPassword()) {
window.location.href="menu_Page.html";
}
else {
alert ("Incorrect Password. Please try again.");
}
}
/*Used in index.html*/
function addValueToPassword(button) {
var currentVal=document.getElementById("passcode").value;
if(button=="bksp") {
document.getElementById("passcode").value=currentVal.substring(0,
currentVal.length-1);
}
else {
document.getElementById("passcode").value=currentVal.concat(button);
}
}
/*Used in User Information page.*/
function checkUserForm() {
var d = new Date();
var month = d.getMonth() 1;
var date = d.getDate();
var year = d.getFullYear();
var currentDate = year '/' (('' month).length<2 ? '0' : '') month '/'
(('' date).length<2 ? '0' : '') date;
if(($("#textFirstName").val() != "") amp;amp; ($("#textLastName").val() != "") amp;amp;
($("#birthDate").val() != "") amp;amp; ($("#phoneNumber").val() != "")) {
return true;
}
else {
return false;
}
}
/*used in User Information page.*/
function saveUserForm() {
if (checkUserForm()) {
var user = {
"FirstName" : $("#textFirstName").val(),
"LastName" : $("#textLastName").val(),
"BirthDate" : $("#birthDate").val(),
"NewPassword" : $("#changePassword").val(),
"PhoneNumber" : $("#phoneNumber").val(),
"Gender" : $("#genders option:selected").val()
};
try {
localStorage.setItem("user", JSON.stringify(user));
alert("User Information Saved.");
window.location.href="file:menu_page.html";
}
catch(e) {
if (window.navigator.vendor==="Google Inc.") {
if (e == DOMException.QUOTA_EXCEEDED_ERR) {
alert("Error: Local Storage limit exceeded.");
}
}
else if (e== QUOTA_EXCEEDED_ERR) {
alert("Error: Saving to local storage.");
}
console.log(e);
}
}
else {
alert("Please complete the form properly.");
}
}
/*used in User Information page.*/
$("#userForm").submit(function() {
saveUserForm();
return true;
});
/*Used in Activity Log page.*/
function showUserInfo() {
var info = JSON.parse(localStorage.getItem("user"));
document.getElementById("showFirstName").innerHTML = info.FirstName;
document.getElementById("showLastName").innerHTML = info.LastName;
document.getElementById("showBirthDate").innerHTML = info.BirthDate;
document.getElementById("showPassword").innerHTML = info.NewPassword;
document.getElementById("showPhoneNumber").innerHTML = info.PhoneNumber;
document.getElementById("showGender").innerHTML = info.Gender;
}
/*Used in New Entry page.*/
function checkEntry() {
var d = new Date();
var month = d.getMonth() 1;
var date = d.getDate();
var year = d.getFullYear();
var currentDate = year '/' (('' month).length<2 ? '0' : '') month '/'
(('' date).length<2 ? '0' : '') date;
if(($("#workDate").val() != "") amp;amp; ($("#recipient").val() != "") amp;amp;
($("#donations").val() != "") amp;amp; ($("#hoursWorked").val() != "")) {
return true;
}
else {
return false;
}
}
/*Used in New Entry page.*/
function saveEntry() {
if (checkEntry()) {
var entry = {
"Date" : $("#workDate").val(),
"Recipient" : $("#recipient").val(),
"Donations" : $("#donations").val(),
"hoursWorked" : $("#hoursWorked").val()
};
try {
var entryList = JSON.parse(localStorage.getItem("entryList"));
if (entryList == null) {
entryList = [];
}
entryList.push(entry);
localStorage.setItem("entryList", JSON.stringify(entryList));
listRecords();
alert("Saving Information");
}
catch(e) {
if (window.navigator.vendor==="Google Inc.") {
if (e == DOMException.QUOTA_EXCEEDED_ERR) {
alert("Error: Local Storage limit exceeded.");
}
}
else if (e== QUOTA_EXCEEDED_ERR) {
alert("Error: Saving to local storage.");
}
console.log(e);
}
}
else {
alert("Please complete the form properly.");
}
return true;
}
/*Used in Activity Log page.*/
function listRecords() {
try {
var entryList=JSON.parse(localStorage.getItem("entryList"));
}
catch(e) {
if (window.navigator.vendor==="Google Inc.") {
if (e== DOMException.QUOTA_EXCEEDED_ERR) {
alert("Error: Local Storage limit exceeded.");
}
}
else if(e==QUOTA_EXCEEDED_ERR) {
alert("Error: Saving to local storage.");
}
console.log(e);
}
if (entryList != null) {
$("#tblRecords").html(
"<thead>"
"<tr>"
"<th>Date Worked</th>"
"<th>Recipients</th>"
"<th>Donations</th>"
"<th>Hours</th>"
"</tr>"
"</thead>"
"<tbody>"
"</tbody"
);
for(var i=0;i<entryList.length;i ) {
var rec=entryList[i];
$("#tblRecords tbody").append("<tr>"
"<td>" rec.Date "</td>"
"<td>" rec.Recipient "</td>"
"<td>" rec.Donations "</td>"
"<td>" rec.hoursWorked "</td>"
"</tr>");
}
}
else {
$("#tblRecords").html("");
}
return true;
}
/*Used in sorting Activity Logs for display.*/
function compareDates(a,b) {
var x = new Date(a.Date);
var y = new Date(b.Date);
if(x>y) {
return 1;
}
else{
return -1;
}
}
/*Used in Activity Log page.*/
function clearActivityLog() {
localStorage.removeItem("entryList");
listRecords();
alert("All records have been deleted.");
}
function graph() {
var entryList=JSON.parse(localStorage.getItem("entryList"));
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "dark2",
title: {
text: "Daily Sales Data"
},
axisY: {
title: "hoursWorked",
titleFontSize: 24,
includeZero: true
},
data: [{
type: "column",
yValueFormatString: "#,### hoursWorked",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i ) {
dataPoints.push({
x: new Date(data[i].Date),
y: data[i].hoursWorked
});
}
chart.render();
}
}
<html>
<head>
<title>Graph Page</title>
<! Links to external stylesheets, jquery, and jquery mobile>
<link rel="stylesheet"
href="jquery.mobile-1.3.1.min.css">
<script src="jquery-1.8.3.min.js"></script>
<script src="jquery.mobil-1.3.1.min.js"></script>
<script type="text/javascript" src="Functions.js"></script>
<! sets width to device-width.>
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div style="margin-top:16px;color:dimgrey;font-size:9px;font-family: Verdana, Arial, Helvetica, sans-serif;text-decoration:none;">Source: <a href="https://canvasjs.com/javascript-charts/json-data-api-ajax-chart/" target="_blank" title="JavaScript Charts amp;amp; Graphs from JSON Data Using AJAX ">https://canvasjs.com/javascript-charts/json-data-api-ajax-chart/</a></div>
</head>
<body onload="graph()">
</body>
</html>
<html>
<head>
<title>Entry Form</title>
<! Links to external stylesheets, jquery, and jquery mobile>
<link rel="stylesheet"
href="jquery.mobile-1.3.1.min.css">
<script src="jquery-1.8.3.min.js"></script>
<script src="jquery.mobil-1.3.1.min.js"></script>
<script type="text/javascript" src="Functions.js"></script>
<! sets width to device-width.>
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
</head>
<body>
<div data-role="page" id="pageHome">
<! Application header is present, including navigation to menu and about pages.>
<div data-role="header"><h1>Mission's Activity Tracker</h1>
<a href="file:menu_Page.html" data-role="button" data-icon="bars" data-iconpos="left"
data-inline="true">Menu</a>
<a href="file:about_page.html" data-role="button" data-icon="info" data-iconpos="right"
data-inline="true">About</a>
</div>
<! Form contains all necessary fields for addition of work entry.>
<form id="actForm" action="">
<! workDate field uses Date input type.>
<div data-role="fieldcontain">
<label for="workDate">Date of Work: </label>
<input type="date" name="workDate"
data-mini="false" id="workDate" value="" required>
</div>
<! Recipient field uses text input type.>
<div data-role="fieldcontain">
<label for="recipient">People ministered to: </label>
<input type="text" placeholder="Enter name(s)." name="recipient"
data-mini="false" id="recipient" value="" required>
</div>
<! donations field uses text input type.>
<div data-role="fieldcontain">
<label for="donations">Items donated: </label>
<input type="text" placeholder="Enter item(s)" name="donations"
data-mini="false" id="donations" value="" required>
</div>
<! hoursWorked field uses number input type.>
<div data-role="fieldcontain">
<label for="hoursWorked">Hours Worked: </label>
<input type="number" placeholder="Enter hours." name="hoursWorked"
data-mini="false" id="hoursWorked" value="" required>
<! After clicking the add entry button, user is redirected back to log page.>
<input type="button" id="btnUserUpdate" data-icon="check" data-iconpos="left"
value="Add Entry" onclick="saveEntry();
window.location.href='file:activity_Log.html'">
</form>
</div>
</div>
</body>
</html>