我正在創建一個購物車,我無法讓jquery和php正常工作。我有一個叫做displayAmount($price)
的函數,它目前只是將數字格式化爲2個小數點,並將英鎊符號添加到它。我希望保留這個功能,因爲我希望能夠允許用戶更改當地貨幣,它將使用此函數來計算並顯示正確的價格和貨幣。使用jquery更改選擇價格,回聲價格與PHP函數
我希望能夠在視圖產品頁面上顯示價格,並在用戶更改選擇框中的選項時更改它。
所以我有這樣的:
的jQuery:
$("select").live('change',function() {
var price = 0;
$("select option:selected").each(function() {
price += parseFloat($(this).data('price'));
});
$('#productPriceLabel').html(price);
});
HTML:
<select class='productSelectOptions'>
<option data-price='+10'>+10</option>
<option data-price='+20'>+20</option>
</select>
<br>
<span id='productPriceLabel'></span>
也能正常工作,以改變價格。不過,我需要能夠使用echo displayAmount($price)
迴應價格我該怎麼做?
感謝
編輯:
function displayAmount($amount)
{
$xamount = str_replace('.', '', $amount);
$type = gettype($xamount);
if($type = integer) {
global $Config;
return $Config['currency'] . number_format($amount, 2);
} else {
return $amount;
}
}
第二個編輯:(FULL CODE)
// Get prices from database
$priceSQL = "SELECT *
FROM shopProductsPrices
WHERE pd_id = '$productId'";
$priceResult = dbQuery($priceSQL);
$priceOptions = "";
$productLowestPrice = 10500;
while($priceRow = dbFetch($priceResult)) {
if($productLowestPrice > $priceRow['spp_price']) { $productLowestPrice = $priceRow['spp_price']; }
$priceOptions .= "<option data-price='+".$priceRow['spp_price']."'>".$priceRow['spp_name']."</option>";
}
if($productLowestPrice == 10500) { $productLowestPrice = 0; }
<table style="border: none; width: 300px;">
<tr>
<td>
<span id="productContentItem">Package:</span>
</td>
<td>
<select class='productSelectOptions'>
<?= $priceOptions ?>
</select>
</td>
</tr>
<tr>
<td>
<span id="productContentItem">Quantity:</span>
</td>
<td>
<select class='productSelectOptionsQty'>
<option value="1">x1</option>
<option value="2">x2</option>
<option value="3">x3</option>
</select>
</td>
</tr>
<tr>
<td>
</td>
<td>
<?= $productAddToBasket ?>
</td>
</tr>
</table>
<span id='productPriceLabel'><?= displayAmount($productLowestPrice) ?></span>
<script>
$(".productSelectOptions").live('change',function() {
var price = 0;
$(".productSelectOptions option:selected").each(function() {
price += parseFloat($(this).data('price'));
$.ajax({
type: "POST",
dataType: "html",
url: '<?= SERV_ROOT ?>library/common.php',
data: '&price='+price,
success: function(returnedData){
$('#productPriceLabel').html(returnedData);
},
error: function(){
$('#productPriceLabel').html('Error Formatting');
}
}); //END Ajax
});
});
</script>
在這裏發表您的PHP函數。 –
已添加到原始文章對不起 – user3306587
當您使用jQuery時,與用戶的交互發生在客戶端(在用戶的瀏覽器中)。所有的PHP腳本都是在服務器端處理的(換句話說,在頁面傳遞給客戶端之前處理PHP)。如果您希望讓用戶在您的網頁上更改貨幣下拉並使用PHP腳本重新格式化您的定價,則需要使用Ajax。請參閱:https://api.jquery.com/jQuery.ajax/ 如果您願意,我可以嘗試詳細說明,但我不能作爲評論。 –