我知道以前曾有人问过类似的问题,但我没有看到适合我的问题的答案。我有一个 div 触发一个存储 id 的 jquery 脚本。我可以将 id 放入 jquery 中的变量中,但我想将该 id 分配给同一页面上存在的 PHP 变量。
到目前为止,这就是我所得到的。这是我存在于 index.php
中的 div:
echo '<div id="'.$unit_id.'" class="dropdown unit '.$unit_size.' unit-'.$unit_number.' '.$unit_status.' data-unit-id-'.$unit_id.'">';
这是我从 functions.php
调用的 jquery:
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
$.ajax({
type: 'post',
data: {id: unit_id}, //Pass the id
});
});
</script>
我想将 unit_id
传递到 index.php
上名为 $getID
的变量中,但我似乎找不到方法进入那里。我尝试过使用帖子,但确实没有提交表单。这只是一个被点击的潜水。
最佳答案
您必须更改您的 id
在你的<div>
并将其设置为获取 jQuery 发送的变量。除此之外,您的 jQuery 脚本看起来不错。
我会这样做:
# Fetch the variable if it's set.
<?php $unit_id = (isset($_POST["id"])) ? $_POST["id"] : null; ?>
# Echo it as the id of the div.
<div id = "<?= $unit_id; ?>" class = "dropdown unit"></div>
编辑:
上面的 PHP 代码等于:
# Fetch the variable if it's set.
<?php
if (isset($_POST["id"])):
$unit_id = $_POST["id"];
else:
$unit_id = null;
endif;
?>
关于javascript - 在同一页面中将值从 jquery 传递到 php 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38137706/