javascript - 在同一页面中将值从 jquery 传递到 php 变量

标签 javascript php jquery ajax

我知道以前曾有人问过类似的问题,但我没有看到适合我的问题的答案。我有一个 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/

相关文章:

javascript - 单选按钮漂浮在我不想要的地方

javascript - 通过垂直进入制作 Div 容器负载

php - 从 JSON 中选择属性

javascript - Jquery tablesorter 插件在 Django 模板中不起作用

php - 如何在 OS X 10.9 上使用 OpenSSL 编译 PHP?

php - 如何在MySQL中表示由产品组成的产品?嵌套集还是其他什么?

javascript - 选择框多选选项无法在 Microsoft Edge 浏览器上使用 JQuery 清除

javascript - Ruby 和 JS 中相同输入的不同和相同正则表达式

javascript - Google 字体未在 PhantomJS 中呈现

javascript - 在脚本中更改 HTML 中输入框的值