【问题标题】:Unable to populate $_SESSION with jQuery无法使用 jQuery 填充 $_SESSION
【发布时间】:2015-07-01 14:47:04
【问题描述】:

我想使用 jQuery 帖子更新 $_SESSION 数据。
最终我将found this script 作为“系统”的基础。

我创建了以下两个文件作为测试:

t1.php:

<?php
session_start();

/* After refresh, src should be visible */
echo print_r($_SESSION);
?>

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />

<script>
$("img.foo").onclick(function()
{
    // Get the src of the image
    var src = $(this).attr("src");

    // Send Ajax request to backend.php, with src set as "img" in the POST data
    $.post("/t2.php", {"img": src});
});
</script>

t2.php:

<?php
session_start();

$_SESSION['imgsrc'] = $_POST['img'];
?>

很遗憾,刷新t1.php后没有生成src路径。
$_SESSION['imgsrc']保持为空。

我已经尝试了一切,也许是为了得到一些东西?
希望你能帮忙!

【问题讨论】:

    标签: php jquery session post


    【解决方案1】:

    您忘记附加文档就绪处理程序 + 它不是 onclick 而是 click,请将其添加到您的代码中:

    <script>
    $(document).ready(function(){
     $("img.foo").click(function()
     {
        // Get the src of the image
        var src = $(this).attr("src");
    
        // Send Ajax request to backend.php, with src set as "img" in the POST data
        $.post("/t2.php", {"img": src});
     });
    });
    </script>
    

    【讨论】:

    • 我还建议使用$("img.foo").on('click', function() { ... }); 来避免这些东西
    • 你没有正确处理 json
    • 确实 @Toumash 我刚刚从 jquery 网站上挑选了这个例子似乎是有效的:$.post( "test.php", { name: "John", time: "2pm" } );
    • 原来@Daan 和 Toumash 是正确的!愚蠢的错误!解决方案是更改 onclick 方法。
    【解决方案2】:

    也许我到处都能看到 json,但这是进行交流的最佳方式。 来自 php 的正确 json 处理将是

    $post= file_get_contents('php://input');
    $json= json_decode($post,true); // true means json will be assoc array  
    

    那么你的脚本就可以修改了:

    <?php
    session_start();
    
    $post= file_get_contents('php://input');
    $json= json_decode($post,true);
    $_SESSION['imgsrc'] = $json['img'];
    ?>
    

    有了它肯定会起作用

    $.ajax({
      type: "POST",
      url: "/t2.php",
      data: {"img": src},
      dataType: "application/json"
    });
    

    【讨论】:

    • 感谢您的建议。这是处理帖子数据的最佳方法吗?将谷歌多一点。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    相关资源
    最近更新 更多