jQuery 和 ajax 在 PHP 中设置会话变量 [英] jQuery and ajax to set session variable in PHP

查看:37
本文介绍了jQuery 和 ajax 在 PHP 中设置会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP 中使用会话变量来管理多语言站点中的当前语言.为了实现我想要的,我使用了一个标志图标,当点击它时(jQuery)它告诉 lang_json.php 将会话变量切换到新语言.

I'm using a session variable in PHP to manage the current language in a multi-language site. To achieve what I want I'm using a flag icon that when clicked (jQuery) it tells lang_json.php to switch the session variable to the new language.

我在 jQuery 方面没有收到错误:

I'm not getting errors on the jQuery side:

var sendData =  'en';  

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "lang_json.php",
    data: ({newLang: sendData}), 
    dataType: "json",
    success: function (msg) {
      alert('Success');
    },
    error: function (err){
      alert('Error');
    }
});

但是 PHP 文件没有设置会话变量:

But the PHP file is not setting the session variable:

lang_json.php:

lang_json.php:

<?php

// Session variables
session_name('aklogin'); // Starting the session
session_start();

if( isset($_POST['newLang']) ){
    $_SESSION['current_lan'] = $_POST['newLang'];
}else{
    $_SESSION['current_lan'] = "Not Posting";
}

?>

会话变量返回未发布".

The session variable is returning "Not Posting".

推荐答案

您声称您正在发送服务器 JSON,但是:

You claim you are sending the server JSON, but:

  • 你不是
  • PHP 未设置为接收 JSON

删除 contentType: "application/json; charset=utf-8",,然后 jQuery 将设置正确的内容类型,PHP 将填充 $_POST.

Remove contentType: "application/json; charset=utf-8",, then jQuery will set the correct content-type and PHP will populate $_POST.

这篇关于jQuery 和 ajax 在 PHP 中设置会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆