2013-03-14 49 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

相關問題