【问题标题】:Setting a session variable in PHP using AJAX使用 AJAX 在 PHP 中设置会话变量
【发布时间】:2016-03-12 22:21:29
【问题描述】:

当用户点击一个 div 后,这个 javascript 函数运行:

$('.test').click(function(e)
    {
        e.preventDefault();
        $.ajax({
            url: 'ajax.php',
            type: 'POST',
            data: {"id": "<?php echo $rows['id']?>"},
            success:function(data){
                window.location.href = 'index.php';
            }
        });
    });

我想将与用户单击的 div 关联的 ID 传递到运行此代码的 ajax.php 文件中:

<?php
    session_start();
    //connect to db here
    $_SESSION['id'] = $_POST['id'];
?>

但是这不起作用。为了进一步扩展我通过获取rows['id'] 变量所做的操作,请运行以下 SQL 代码:

$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);

然后我输出了一堆 id 对应的 div:

<?php
    while ($select_rows = mysqli_fetch_array($results_select))
    {
        echo "<div class = 'test'></div>";
    }
?>

有谁知道我如何做到这一点?

【问题讨论】:

    标签: javascript php jquery sql ajax


    【解决方案1】:

    使用数据属性:

    试试:

    <?php
        while ($select_rows = mysqli_fetch_array($results_select))
        {
            echo "<div data-id='".$rows['id']."' class = 'test'></div>";
        }
    ?>
    

    js:

    $('.test').click(function(e)
        {
            e.preventDefault();
            $.ajax({
                url: 'ajax.php',
                type: 'POST',
                data: {"id": $(this).attr('data-id')},//fetch the data attribute 
                success:function(data){
                    window.location.href = 'index.php';
                }
            });
        });
    

    【讨论】:

    • 不幸的是仍然收到此错误:Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'id']?&gt;''
    • 在我的代码中我没有任何 &lt;?php echo $rows['id']?&gt; 复制我的代码
    • 我编辑了上面的代码,我找到了错误发生的位置,它在我的 WHERE 语句中:WHERE id = '$id'"; 据我了解,该语法没有任何问题
    • 所以我知道 id 没有被存储到会话变量中
    【解决方案2】:

    请检查 data: {"id": "&lt;?php echo $rows['id']?&gt;"} 的 JS 代码。此行可能无法传递您的实际值,因此将其存储到具有 id 属性的 div 中,并通过 jQuery 获取并传递它。

    JS:

    $('.test').click(function(e)
    {
        dataValue = $(this).attr('id');//Get user clicked div id attribute value...
        e.preventDefault();
        $.ajax({
            url: 'ajax.php',
            type: 'POST',
            data: {"id": dataValue},
            success:function(data){
                window.location.href = 'index.php';
            }
        });
    });
    

    PHP:

    使用上述 JS 代码,您还需要对 PHP 代码进行一些更改:

    while ($select_rows = mysqli_fetch_array($results_select))
    {
        echo "<div class = 'test' id='". $select_rows['id'] ."'></div>";
    }
    

    请在 AJAX 后处理程序页面上通过print_r($_POST); 确认此代码。这将打印 AJAX 代码请求的 POST 数据。

    如果对此有任何疑虑,请告诉我。

    【讨论】:

      猜你喜欢
      • 2018-04-04
      • 1970-01-01
      • 2015-04-07
      • 2015-10-10
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      相关资源
      最近更新 更多