如何使用ajax将javascript变量分配给php变量 [英] how to use ajax to assign javascript variable to php variable

查看:60
本文介绍了如何使用ajax将javascript变量分配给php变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能,我想使用Ajax将变量"Quantity"分配给php变量,但是,我对ajax的了解不是很多,所以有人可以给我代码来完成这项工作.谢谢

I have the following function and I am wanting to assign the variable "Quantity" to php variable using Ajax but, I am not don't know much about ajax so can someone please give me the code that will do the job. Thanks

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]中减去数量变量

I want the quantity variable to be subtracted from the $row[item_amount] from the server

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);

推荐答案

有很多方法.您可以使用PHP会话变量来执行此操作.您可以使用下面的代码段保存一个 POST 变量,并将其另存为PHP会话变量.

There are ways. You can use PHP session variables to do this. You can use the snippet below to save a take a POST variable and save it as a PHP session variable.

<?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,因此我们将这样做:

Now you need your JavaScript to connect to the PHP script and, it looks like you're using jQuery already, so we'll do it like this:

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

上面的JS代码片段要求PHP脚本将 $ _ SESSION ['foo'] 保存为'bar'.接收到数据后,您的浏览器的JavaScript控制台将显示 true false ,具体取决于值是否已保存.

The JS snippet above asks the PHP script to save $_SESSION['foo'] as 'bar'. When the data has been received, your browser's JavaScript console displays either true or false, depending on if the value has been saved or not.

这篇关于如何使用ajax将javascript变量分配给php变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆