所以昨天我发现了在加载后调用另一个函数的可能性。现在,我正试图从加载的页面生成一个php变量。这是代码——我想我只是少了几行左右。
function compute(id)
{
var qty=document.getElementById('qty'+id).value;
$("#sub"+id).show();
$("#sub"+id).load('subtotal.php?qty='+qty+'&cartid='+id, function (total) {
document.getElementById('totalholder').value = total;
});
}
这是subtotal.php.
<?php
require("connect.php");
session_start();
$qty=$_GET['qty'];
$cartid=$_GET['cartid'];
$id=$_SESSION['ID'];
$query=mysql_query("update tblcart set quantity=$qty where CartID = $cartid and UserID=$id");
mysql_query("update tblcart set subtotal=price*quantity where CartID = $cartid and UserID=$id");
$x=mysql_fetch_array(mysql_query("Select Subtotal from tblcart where CartID = $cartid and UserID=$id"));
$total=mysql_fetch_array(mysql_query("Select SUM(Subtotal) As Total from tblcart where UserID = $id"));
?>
<div id="<?php echo "sub".$cartid;?>" style="width:100%;float:left;">
<?php echo "Php ".number_format ( $x['Subtotal'], 2, '.', ','); ?>
</div>
<script>
return (<?php $total; ?>);
</script>
我想返回php变量$total到函数,以便能够在load()之后使用它。帮助是非常感激,并提前感谢您!xx
http://api.jquery.com/load/
这是你错过的
.load()将匹配元素的HTML内容设置为返回的内容数据。这意味着该方法的大多数用途可以非常简单:
document.getElementById('totalholder').value = total;
$('#totalholder').val(total);
但是,想象一下它在load函数
之外的自己的脚本标签中<script type="text/javascript" >
return (<?php $total; ?>);
</script>
所以你只是返回总数到稀薄的空气
你可以做
<script type="text/javascript" >
alert(<?php $total; ?>);
</script>
但是像这样的东西是你想要的
<script type="text/javascript" >
$('#totalholder').val(<?php $total; ?>);
</script>
假设你有一个元素#totalholder
更新:然后我要做的是在返回的html中的元素中设置总数,跳过返回的html中的JavaScript,然后从回调
中访问它如果提供了一个"complete"回调,它将在之后执行进行了后处理和HTML插入。回调函数是为jQuery集合中的每个元素触发一次,这是设置的到每个DOM元素。
所以在返回的html。
<input type="hidden" id="total" value="<?php echo $total; ?>"/>
和回调
$("#sub"+id).load('subtotal.php?qty='+qty+'&cartid='+id, function () {
/*The callback is
fired once for each element in the jQuery collection, and this is set
to each DOM element in turn.*/
if($(this).prop('id') == 'total'){
var total = $(this).val();
}
});
需要注意的是,我通常不使用.load(),而主要使用$。帖子,美元。得到等。
我想你可以做到这一点,只要一个简单的$.get()
:
function compute(id)
{
$.get('subtotal.php', {
qty: $('#qty' + id).val(),
cartid: id
}, function(data) {
$('#sub' + id).text(data.subtotal).show();
$('totalholder').val(data.total);
});
}
然后,PHP返回一个JSON编码的主体:
header('Content-Type: application/json');
echo json_encode(array(
'subtotal' => $x['Subtotal'],
'total' => $total['Total'],
));