如何使用ajax将javascript变量分配给PHP变量

how to use ajax to assign javascript variable to php variable

本文关键字:变量 分配 PHP javascript 何使用 ajax      更新时间:2023-09-26

我有以下功能,我想使用Ajax分配变量"数量"到php变量,但是,我不是对Ajax不太了解,所以可以有人请给我的代码,将做这项工作。由于

var Quantity;
$("select").change(function() {
  var str = "";
  var price = <?php echo $row[price];?>;
  $("select option:selected").each(function() {
    str += $(this).text() + " ";
  });
  $(".plan_price").text("price : " + parseInt(str) * price + " baht");
  Quantity = parseInt(str);
}).change();
function selectOne() {
  var select = document.getElementById('quantity');
  for (var i=0; i<<?php echo $row[item_amount]?>; i++) {
    select.options[select.options.length] = new Option(i+1, i);
  } 
}

我想从服务器的$row[item_amount]中减去quantity变量

if ($row[item_amount] - Quantity  == 0) {
   $sql = "update item set active='2',item_amount=item_amount-Quantity,buy_time=NOW() where id='$id'";
} else {
   $sql = "update item set item_amount=item_amount-Quantity,buy_time=NOW() where id='$id'";
}
$result = mysql_query($sql);

add this:

:

...
Quantity = parseInt(str);
$.ajax({url:"yourphp.php",type:"POST",async:false,data:{quantity:Quantity}});

在你的PHP:

...
$Quantity = $_POST["quantity"];
if ($row[item_amount] - $Quantity  == 0) {

我不知道"数量"在你的mysql查询是指发送的$数量通过javascript;

有很多方法。您可以使用PHP会话变量来做到这一点。您可以使用下面的代码片段来保存一个POST变量,并将其保存为PHP会话变量。

<?php
header('Content-Type: application/json; charset=UTF-8');
session_start();
if ($_POST['foo'] == true) {
  $_SESSION['foo'] = $_POST['foo'];
  echo json_encode(true);
}
else {
  echo json_encode(false);
}
?>

现在你需要你的JavaScript连接到PHP脚本,看起来你已经使用jQuery了,所以我们将这样做:

$.post('/_/ajax/init_session.php', { foo: 'bar' }, function(data) {
  console.log(data);
}, json);

上面的JS片段要求PHP脚本将$_SESSION['foo']保存为'bar'。当接收到数据时,浏览器的JavaScript控制台显示truefalse,这取决于值是否已保存。