我是PHP的新手,对JQuery来说还是新手。
所以我写了一些做一些计算的JQuery,我在下面写了类似的东西:
//on change of a selectbox with the class item
$('.item').change(function() {
// set variable id as the id name of this id
var id = this.id;
// price variable is equal to the value of the element id 'hiddenprice'
price = $("#hiddenprice").val();
// number of items is the value of the select box
numberofitems = $(this).val();
// number of days is equal to a php variable I set on the page
numofdays = "<?php echo $length->days; ?>";
//totalprice is equal to the 'price' multiplied by 'numofdays'
totalprice = Number(price) * Number(numofdays);
//calculates final total by multiplying the 'totalprice' by 'numofitems'
finaltotal = Number(totalprice ) * Number(numofitems);
//updates the HTML with the new price
$('#'+id).html("€" + finaltotal.toFixed(2));
});
我正在尝试这个,虽然我得到它的工作,在阅读了一些我知道,因为这个脚本在我的页面的页脚正在更新,它是不安全的,如果用户想要操作容易操作恶意的
所以我想通过将值发布到PHP脚本然后返回值来进行计算服务器端。
// POST values to PHP Script
$id = (posted select id);
$price = (#hiddenprice variable value);
$numofitems = (posted value of the select);
$numofdays = $length->days;
$totalprice = (int)$price * (int)$numofdays;
$finaltotal = (int)$totalprice * (int)numofitems;
//Then push $finaltotal and $id back to the user viewed page
$('#'+<?php echo $id; ?>).html("€" + <?php echo $finaltotal; ?>.toFixed(2));
我只是不确定如何将它们推送到页面而不刷新然后返回它们,也没有刷新。
再次,抱歉,如果这很简单,我已经看过JQuery表单插件,我只是想知道是否有更多适合我想做的解决方案。
提前致谢。
答案 0 :(得分:1)
您可能需要查看ajax,它可以在不刷新页面的情况下发布或获取数据。 this question的答案也可能有所帮助。
答案 1 :(得分:0)
您需要使用AJAX。这会将数据发送到服务器,并允许您在收到响应后执行回调。
如果您使用的是jQuery,请阅读$.ajax方法。
要处理响应,最简单的数据类型是JSON。
这是一个简单的例子
<强>的Javascript 强>
$.ajax({
url: calculation_url.php,
method: 'post',
dataType: 'JSON',
data: {price: price, days: numofdays },
success: function(response) {
// you should check a valid response was received
$("#result").html(response.html);
}
});
PHP - calculatin_url.php
$price = $_POST['price'];
$days = $_POST['days'];
// do calculations
// send data back as json
die(json_encode(array('html' => $finalTotal)));
要开始此过程,您需要将事件附加到计算按钮。阅读有关使用on方法注册活动的信息,您可能会发现阅读event.preventDefault()方法很有帮助。