在下拉列表中使用ajax设置会话变量

时间:2016-09-27 10:57:14

标签: php ajax

伙计这让我发疯了。每个人都在关闭我的问题,说它已被问到但是我无法理解它,因为我是ajax和php的新手。

我正在下拉选择事件进行ajax调用:

$('#username').change(function () {
    var user = $('#username').val();
    $.ajax({
        type: 'POST',
        url: 'sessionvar.php',
        data: {username: user},
        success: function (msg) {
          alert('Success');
        }
  });
});

我正在获得成功警报。 但是在php页面上,变量没有设置。

PHP代码是:

<?php
session_start();
if( isset($_POST['username']) ){
    $_SESSION['cellValue'] = $_POST['username'];
}else{
    $_SESSION['cellValue'] = "good";
}

echo $_SESSION['cellValue'];
?>

代码始终打印价值不错。

我的整个HTML代码:

<!DOCTYPE html>
<html>
    <head>
        <title>FusionCharts Column 2D Sample</title>
    </head>
    <body>
        <?php
            session_start();
        ?>
        <div>
         // This will echo a select with name username. and when a value is
         // selected the below ajax call is made.
            <?php
                require("userList.php");
            ?>
        </div>
        <button type="button">Click Me</button>
        <div id="chart-container">LOADING....</div>
        <script src="js/jquery-2.2.4.js"/>
        <script src="js/fusioncharts.js"/>
        <script src="js/fusioncharts.charts.js"/>
        <script src="js/themes/fusioncharts.theme.zune.js"/>
        <script type="text/javascript">
    $(document).ready(function(){

   $('#username').change(function () {
    var user = $('#username').val();
    $.ajax({
        type: 'POST',
        url: 'sessionvar.php',
        data: {username: user},
        success: function (msg) {
          alert(msg);
        }
  });

});
   });
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

    <?php 
session_start();
if(isset($_POST['username']))
{
    $_SESSION['cellValue'] = $_POST['username'];
    echo $_SESSION['cellValue'];die;
}?>
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<select class="abc">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<script>
    $(document).ready(function()
    {
        $('.abc').on('change', function() 
        {
             var user = $( ".abc option:selected" ).val();
             $.ajax({
                    type: 'POST',
                    url: 'test.php',
                    data: {username: user},
                    success: function (data) {
                      alert(data);
                    }
              });
        });
    });
</script>