[英]How to pass jquery variable value to php variable?
這是我的javascript。 我想使用ajax將jQuery變量值轉換為同一頁面中的php變量。 我曾經打印過php變量,但是有錯誤。 如果有人可以幫助我,我將不勝感激。
<script type="text/javascript">
$(document).ready(function() {
$('#roomOptions #select1').change(function() {
var total = 0;
$('#roomOptions #select1').each(function() {
total+=parseInt($(this).val());
});
$('#roomOptions #roomOptions_total').html(total);
});
$('#roomOptions #select2').change(function() {
var total1 = 0;
$('#roomOptions #select2').each(function() {
total1+=parseInt($(this).val());
});
$('#roomOptions #roomOptions_total1').html(total1);
});
});
$.ajax({
type: "POST",
url: "getrooms.php",
data:{ total: total },
success: function(data){
console.log(data);
}
})
</script>
您應該這樣添加PHP:
<?php
$total = $_POST['total'] ;
echo $total;
?>
根據問題作者的評論添加編輯內容。
由於您使用同一頁面通過jquery發布數據,因此應刷新頁面。 像這樣為ajax調用修改代碼(javascript部分)。
$.post(window.location, {title: title}, success: function(data) {
//do something here
});
並將其添加到頁面代碼的頂部。
<?php
if(isset($_POST['total'])) {
echo $_POST['total'];
}
?>
順便說一句,您的total
變量只能通過更改方法匿名回調函數來訪問! total
將在您的ajax調用中undefined
。
$('#roomOptions #select1').change(function () {
var total = 0;
$('#roomOptions #select1').each(function () {
total += parseInt($(this).val());
});
$('#roomOptions #roomOptions_total').html(total);
$.ajax({
url: getrooms.php,
type: 'POST',
data: {
"total": total
}
});
});
您應該在函數之前用JavaScript聲明“ total”變量。
var total = 0;
$('#roomOptions #select1').change(function () {
total = 0;
$('#roomOptions #select1').each(function () {
total += parseInt($(this).val());
});
$('#roomOptions #roomOptions_total').html(total);
});
或者像這樣在ajax init之前獲取它
<script>
total = $("#roomOptions #roomOptions_total").html();
$.ajax({
type: "POST",
url: "getrooms.php",
data:{ total: total },
success: function(data){
console.log(data);
}
})
</script>
您可以在php中訪問您的var
<?php echo $_POST['total']; ?>
在ajax發送之前,您可以查看里面的總計
<script>
total = $("#roomOptions #roomOptions_total").html();
$.ajax({
type: "POST",
url: "getrooms.php",
data: { total: total },
success: function(data){
console.log(data);
},
beforeSend: function() {
console.log(total);
}
})
</script>
我認為問題出在您的代碼序列上。 在調用document.ready之前進行ajax調用。 如果您將其轉換為類似的內容,則可能會起作用
<script type="text/javascript">
$(document).ready(function() {
var total = 0;
$('#roomOptions #select1').change(function() {
total = 0;
$('#roomOptions #select1').each(function() {
total+=parseInt($(this).val());
});
$('#roomOptions #roomOptions_total').html(total);
});
$('#roomOptions #select2').change(function() {
var total1 = 0;
$('#roomOptions #select2').each(function() {
total1+=parseInt($(this).val());
});
$('#roomOptions #roomOptions_total1').html(total1);
});
$.ajax({
type: "POST",
url: "getrooms.php",
data:{ total: total },
success: function(data){
console.log(data);
}
})
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.