2013-03-14 67 views
0

我对PHP相当陌生,对JQuery来说真的很陌生。PHP/JQuery:发布到PHP脚本,然后返回值并使用JQuery更新HTML

所以我写诗一些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("&euro;" + 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("&euro;" + <?php echo $finaltotal; ?>.toFixed(2)); 

我只是不知道如何将它们推到网页不刷新的情况,然后返回他们,也没有刷新。

再次,抱歉,如果这很简单,我已经看过JQuery表单插件,我只是想知道是否有更多适合我想要做的解决方案。

在此先感谢。

回答

1

您可能想查看ajax,它可以发布或获取数据而无需刷新页面。 this question的答案也可能有帮助。

+0

我使用了像你说的在jQuery中的ajax,然后echo'd一个变量 – TryingToBeZen 2013-03-14 15:40:32

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()方法很有帮助。

+0

对不起,我没有看到这个或我会接受它作为答案,必须接受,就像我接受。 – TryingToBeZen 2013-03-14 15:41:58

+0

@TryingToBeZen你可以改变你接受的答案 – 2013-03-15 01:28:11

相关问题