根据页面中设置的值在 php 中设置会话

Setting session in php from value being set in the page

我正在尝试设置 php 会话加载

 $_SESSION["tusername"] = $_POST['ttuser'];

但是我的值是在 $(function() {

的 jQuery 中设置的
 $('#ttuser').val(tusername);

加载页面时,会话未设置,因为我相信会话是在 jQuery 设置文本框值之前设置的。我尝试使用 ajax 到 post 页面的值,但它没有检索它。

我现在设置会话的唯一方法是单击按钮,方法完全相同。

有什么想法吗?

提前致谢

编辑 这是开头的函数,按照要求设置了所有内容

$(function() {
  // Initialize. If we are already logged in, there is no
  // need for the connect button
  Twitch.init({clientId: CLIENT_ID}, function(error, status) {
    if (status.authenticated) {
      // we're logged in :)


      $('.authenticatedd').removeClass('hidden');
    } else {
      $('.welcometitle').html('<strong>Not yet connected with Twitch?</strong>');

      // Show the twitch connect button
      $('.authenticate').removeClass('hidden');
    }
  });


var token = Twitch.getToken();
      $('.twitch-connect').click(function() {
        Twitch.login({
          scope: ['user_read', 'channel_read', 'channel_editor', 'channel_commercial', 'user_subscriptions', 'channel_check_subscription']
        });
      })

Twitch.api({method: 'channel'}, function(error, channel) {
      $('#streamkey').text(channel.stream_key);
    });


    Twitch.api({method: 'user'}, function(error, user) {
    var tusername = user.display_name;
    var tlogo = user.logo;
    $('#twitchname').text(tusername);
    $('#ttuser').val(tusername);
$.get("setsession.php?ttuser="+tusername, function(){

});
    console.log(tlogo);

    if (tlogo != null)
    $('#twitchlogo').attr('src', tlogo);
$.cookie('logo', tlogo, { expires: 14, path: '/'});

    $('.sidename').html('<strong>' + tusername + '</strong> Logged in');
    var currentdate = new Date(); 
    var datetime = currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();    
    var items = [];
 items.push('<li><div class="xe-comment-entry"><div class="xe-comment"><a href="#" class="xe-user-name"><span class="label label-success">Status</span></a><p><span class="label label-danger">' +datetime+ '</span> Logged in</p></div></div></li>')
 $('#eventlog').prepend( items.join('') );
    });

});

您为什么不直接向 php 文件发出请求以启动会话。

myfile.php

<?php
session_start();
$_SESSION["tusername"] = $_REQUEST['ttuser'];
echo "Session is : "+$_SESSION["tusername"];
?>

HTML

$(function(){
$.get("myfile.php?ttuser="+tusername, function(data){
console.log(data);
});
 $('#ttuser').val(tusername);
});