设置session从jquery到php的session


set session from jquery to session in php

我有一个页面在PHP执行查询。当我需要从另一个页面使用jquery会话参数。那么,如何在PHP中从jquery的session中设置session。请检查我的代码并给我解决方案。谢谢…

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.ciphertrick.com/demo/jquerysession/js/jquerysession.js?d56ac9"></script>
<script>
$(document).ready(function(){ 
var sDecode = $.session.get("sesDecode"); 
alert(sDecode);      
}); 
</script> 
<?php
include('connection.php');  
$content= ==> how to get " sDecode " ???
$upd = mysql_query("UPDATE t_modules set content='$content' where id_t_modules='3'") or die(mysql_error());  
?>

您可以使用ajax向php文件发送参数,如下所示

$.ajax({
        url: "connection.php", 
        data: "Session="+$.session.get("sesDecode"), 
        type: "POST", 
        dataType: 'json',
        success: function (e) {
            console.log(JSON.stringify(e));
        },
        error:function(e){
            console.log(JSON.stringify(e));
        }
    });

注意,这两种解决方案都需要检查输入,因为用户可能会修改它。

使用Ajax

获得sDecode的最佳方法可能是通过jQuery.post() (AJAX)将其发送到PHP页面,该页面将注册会话值(在对其进行适当的检查之后)。

$.post('session.php', { d: sDecode }, function (response) {
      alert(response);
});

在PHP中通过:

$sDecode = $_POST["d"]; // Please test the input here!

您可能必须使用.serialize(),然后在PHP中反序列化它,这取决于内容和您如何处理它。

使用重定向

您可以简单地重定向到一个页面,并将其作为GET值直接传输:

window.location.href=”session.php?d="+sDecode;

然后在session.php页面上使用以下代码读取:

$sDecode = $_GET["d"]; // Please test the input here!

您可以让PHP从会话变量中填充Javascript变量。

<?php session_start(); ?>
<html>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
    var sDecode = <?php echo json_encode($_SESSION['sDecode']); ?>;
    alert(sDecode);
</script>

PHP在Jquery之前执行,所以在从session获取参数后使用ajax来执行查询