我有一个JavaScript计算器,它从用户那里获取值但是没有这些的html输入字段,我想将这些值存储到MySQL数据库中。但我认为不使用PHP,我不能这样做。有没有办法直接将这些值放到MySQL数据库中,或者我可以在PHP中访问这些变量。请为此提出一些解决方案。
var budget_calculator = (function($){
//Set the default incomes and outgoings here
var defaultsObj = {
'income':{
1:{name:"Maintenance Loan",freq:12,value:0},
2:{name:"Scholarships",freq:12,value:0},
3:{name:"Work Income",freq:12,value:0},
4:{name:"Parental Support",freq:12,value:0},
5:{name:"Other",freq:12,value:0},
},'outgoings':{
1:{name:"Rent",freq:12,value:0},
2:{name:"Bills",freq:12,value:0},
3:{name:"Groceries",freq:12,value:0},
4:{name:"Commuting",freq:12,value:0},
5:{name:"Phone",freq:12,value:0},
6:{name:"Books",freq:12,value:0},
7:{name:"Stationary",freq:12,value:0},
8:{name:"Going Out",freq:12,value:0},
9:{name:"Hobbies",freq:12,value:0},
10:{name:"Gym",freq:12,value:0},
11:{name:"Other",freq:12,value:0}
}
};
//Functions to store and retrieve objects from localstorage
function ls_store(name,o){
localStorage.setItem(name, JSON.stringify(o));
};
function ls_read(name){
return JSON.parse(localStorage.getItem(name));
};
//Format a currency string
function format_currency(num) {
var p = num.toFixed(0).split(".");
return "£" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
return num + (i && !(i % 3) && !(num=='-') ? "," : "") + acc;
}, "");
}
function set_defaults(){
ls_store('bc_expenses',defaultsObj);
expensesObj = ls_read('bc_expenses');
}
//If our localstroage items are empty let's store the defaults
if(ls_read('bc_expenses')==null){
set_defaults();
}
var expensesObj = ls_read('bc_expenses');
//Reset the localstorage if the clear link is clicked
$('.reset-localstorage').click(function(e) {
e.preventDefault();
set_defaults();
display_tables();
});
//Set our frequencies object
var frequenciesObj = {52:"Weekly", 26:"Fortnightly", 12:"Monthly", 4:"Quarterly", 1:"Annually"};
function display_percents(element_class, value, percent){
$('#totals '+element_class+' > h3 > span').html(format_currency(value));
$('#totals '+element_class+' .progress-bar').html('<span class="percent">' + percent.toFixed(2)+'%</span>')
if(percent<0){
$('#totals '+element_class+' .progress-bar').css('width',(percent*-1)+'%').addClass('progress-bar-danger');
}else{
$('#totals '+element_class+' .progress-bar').css('width',percent+'%').removeClass('progress-bar-danger');
}
}
function calc_totals(){
var income_total = 0;
var outgoings_total = 0;
for(var i in expensesObj['income']){
var e = expensesObj['income'][i];
//income_total = income_total+e.value * e.freq;
income_total = income_total+e.value * e.freq ;
}
for(var i in expensesObj['outgoings']){
var e = expensesObj['outgoings'][i];
outgoings_total = outgoings_total+e.value * e.freq;
}
var outgoings_percent = (outgoings_total/income_total)*100;
var income_percent = 100-outgoings_percent;
var savings_total = parseInt(income_total - outgoings_total,10);
var savings_percentage = (savings_total/income_total)*100;
display_percents('.total-income', income_total, income_percent);if(isNaN(income_percent)){display_percents('.total-income', 0, 0)}
display_percents('.total-outgoings', outgoings_total, outgoings_percent);if(isNaN(outgoings_percent)){display_percents('.total-outgoings', 0, 0)}
display_percents('.total-savings', savings_total, savings_percentage);if(isNaN(savings_percentage)){display_percents('.total-savings', 0, 0)}
}
//Function to calculate the incomes or outgoings
function calc_costs(){
for(var type in expensesObj){
var total = 0;
$('.budget-calculator #'+type+' tbody tr').each(function() {
var amount = $(this).find('.amount').val();
var freq = $(this).find('.freq').val();
var single_total = amount*freq;
var row_id = $(this).attr('data-id');
if(!isNaN(single_total)){
total = total + single_total;
$('#'+type+' tbody tr[data-id="'+row_id+'"]').find('.single-total').html(''+format_currency(single_total));
$('#'+type+' tfoot .total').html('Total yearly '+type+': '+format_currency(total));
expensesObj[type][row_id].value=amount;
expensesObj[type][row_id].freq=freq;
ls_store('bc_expenses',expensesObj)
}
});
}
calc_totals();
}
//Display the incomes/outgoings objects as a table
function display_tables(){
for(var type in expensesObj){
var d = '';
for(var i in expensesObj[type]){
d+='<tr data-id="'+i+'" data-type="'+type+'">'+
'<td>'+expensesObj[type][i].name+':</td>'+
'<td><select class="freq">';
for(var f in frequenciesObj){
var selected = '';
if(expensesObj[type][i].freq == f){selected = ' selected';}
d+='<option value="'+f+'" '+selected+'>'+frequenciesObj[f]+'</option>';
}
d+='</select></td>'+
'<td><input class="amount" type="text" maxlength="8" value="'+expensesObj[type][i].value+'"/></td>'+
'<td><span class="single-total">$0</span></td>'+
'<td><span class="remove-row"><i class="glyphicon glyphicon-trash"></i></span></td>'+
'</tr>';
}
$('.budget-calculator #'+type+' tbody').html(d);
}
calc_costs();
}
$('.nav-tabs a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
//text value get's changed
$('.budget-calculator').on('keyup','tbody .amount',function(e) {
var type= $(this).closest('.tab-pane').attr('id')
calc_costs()
});
//Frequency gets changed
$('.budget-calculator').on('change','tbody .freq',function(e) {
var type= $(this).closest('.tab-pane').attr('id')
calc_costs()
});
//Add a row button get's clicked - launch the bootstrap modal
$('.budget-calculator').on('click','.add-row',function(e) {
var type= $(this).attr('data-type');
$('#budget-calculator-add-row .btn-add-row').attr('data-type',type)
$('#budget-calculator-add-row label').text('Enter name for '+type)
$('#budget-calculator-add-row').modal();
});
//Add a new row
$('#budget-calculator-add-row .btn-add-row').click(function(e) {
var val = $('#add-row-name').val();
var type= $(this).attr('data-type');
if(val.length>0){
//Lets add the row
for(var i in expensesObj[type]){
var new_index = parseInt(i,10)+1;
}
expensesObj[type][new_index] = {name:val,freq:12,value:0}
ls_store('bc_expenses',expensesObj);//Store the object
display_tables();
calc_costs();
$('#add-row-name').val('')
$('#budget-calculator-add-row').modal('hide');
}else{
console.info('No value Entered so will not save!');
}
});
//Remove a row
$('.budget-calculator').on('click','.remove-row',function(e) {
var type= $(this).closest('tr').attr('data-type');
var id= $(this).closest('tr').attr('data-id');
delete expensesObj[type][id];
ls_store('bc_expenses',expensesObj);//Store the object
display_tables();
calc_costs();
})
//Display the objects as HTML in the forms
display_tables()
})(jQuery);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Financhester</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<!-- Budget Calculator CSS -->
<link rel="stylesheet" href="budget-calculator.css" type="text/css" />
</head>
<body>
<div class="header">
<h1>Financhester</h1>
<h4>Student-Friendly Budgeting Tool</h4>
</div> <!-- endHeader -->
<div class="topnav">
<a class = "active" href="index.html">Home</a><a href="AmeliaPage/advice page/advice-recommended-apps.html">Deals & Money Advice</a><a href="about.html">About</a>
</div><!-- topNav -->
<div class = "wrapper">
<br>
<h4>How to use Financhester:
<ol>
<li>Enter your income, loans and sholarships/bursaries where applicable.</li>
<li>Enter your estimated expenses.</li>
<li>See your balance down below!</li></h4>
</ol>
<br>
<div class="clear_float">
</div>
<!-- ############# BEGIN Budget Calculator HTML ############# -->
<div class="budget-calculator">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li class="active"><a href="#income" role="tab" data-toggle="tab">INCOME</a></li>
<li><a href="#outgoings" role="tab" data-toggle="tab">EXPENSES</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane fade in active" id="income">
<table class="table table-hover">
<thead>
<tr>
<th>Income Type</th>
<th>Frequency</th>
<th>Amount</th>
<th>Annual Amount</th>
<th> </th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr><td colspan="100"><span class="btn btn-md btn-primary add-row" data-type="income"><i class="glyphicon glyphicon-ok-circle"></i> add another source of income</span></td></tr>
<tr><td colspan="100"><span class="total">Total: £0</span></td></tr>
</tfoot>
</table>
</div><!-- tab-pane -->
<div class="tab-pane fade" id="outgoings">
<table class="table table-hover">
<thead>
<tr>
<th>Expenses Type</th>
<th>Frequency</th>
<th>Amount</th>
<th>Annual Amount</th>
<th> </th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr><td colspan="100"><span class="btn btn-md btn-primary add-row" data-type="outgoings"><i class="glyphicon glyphicon-ok-circle"></i> add another type of expenses</span></td></tr>
<tr><td colspan="100"><span class="total">Total: £0</span></td></tr>
</tfoot>
</table>
</div><!-- tab-pane -->
<div class="" id="totals">
<div class="totals total-income">
<h2>Your balance</h2>
<h3>Annual Income: <span>£0</span></h3>
<div class="progress progress-striped active">
<div class="progress-bar" style="width:0%"></div>
</div>
</div>
<div class="totals total-outgoings">
<h3>Annual Expenses: <span>£0</span></h3>
<div class="progress progress-striped active">
<div class="progress-bar" style="width:0%"></div>
</div>
</div>
<div class="totals total-savings">
<h3>Annual Balance: <span>£0</span></h3>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-success" style="width:0%"></div>
</div>
</div>
</div><!-- tab-pane -->
</div><!-- tab-content -->
<!-- bootstrap modal -->
<div class="modal fade" id="budget-calculator-add-row">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Add row</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="add-row-name">Type of Expenses</label>
<input type="text" class="form-control" id="add-row-name" placeholder="">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary btn-add-row" data-type="">Add Row</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div> <!-- .budget-calculator -->
<!-- ############# END Budget Calculator HTML ############# -->
</div><!-- wrapper -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<!-- Budget Calculator JS -->
<script src="budget-calculator.js">
</script>
<div class="footer">
<br>
<a href="privacy.html">Privacy policy</a> <a href="terms.html">Terms and Conditions</a>
<br>
<br>
<p>© 2018 Z1 ALL RIGHTS RESERVED</p>
</div><!-- ###### footer ###### -->
</body>
</html>
答案 0 :(得分:1)
这里有很多代码。没有经过所有内容,这里是使用PHP,MySQL,jQuery和AJAX将计算器值插入数据库的一个非常基本的例子。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var value = ?? // the return value from the calculator
$.ajax({
data: {value: value},
type: "POST",
url: "http://example.com/insert.php",
success: function(data){
alert('Successfully saved into database.');
}
});
</script>
// insert.php:
<?php
$stmt = $dbh->prepare("INSERT INTO table (value) VALUES (:value)");
$stmt->bindParam(':value', $_POST['value']);
$stmt->execute();
?>