php会话无法与ajax一起使用 [英] php session not working with ajax

查看:51
本文介绍了php会话无法与ajax一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,那就是php会话变量在ajax访问的页面上不起作用.

I've got a weird problem were php session variables are not working on pages accessed by ajax.

服务器端代码: s2.php

<?php
    session_start();
    header("Access-Control-Allow-Origin: *");

    echo '{"response":"'.$_SESSION["email"].'"}';

    exit();
?>

客户端代码: index.php

$.ajax({
    url: 'mysite.com/s2.php',
    data: info,
    error: function() {
        console.log("broke :( ");
    },
    dataType: 'json',
    success: function(data) {
        console.log(data);
    },
    type: 'POST'
});

当我导航至mysite.com/index.php时,我在控制台中看到: {response:"} .

when I navigate to mysite.com/index.php i see: {response: ""} in the console.

导航到mysite.com/s2.php时,我在浏览器中看到 {response:"email @ address"} .

When I navigate to mysite.com/s2.php I see {response: "email@address"} displayed in the browser.

我只是不明白为什么 s2.php 可以正常访问会话,但是通过ajax调用无法访问该会话.

I just don't understand why s2.php can access the session normally but not when run by an ajax call.

此外,当我在家庭服务器上运行它时,一切似乎都很好.但是这是在我妻子的bluehost.com服务器上运行时,它才出现问题.这些与他们的设置有关吗?

Also, when I run it on my home server, everything seems fine. But it's when it's run on my wife's bluehost.com server is when it has problems. Is this something with their settings?

推荐答案

根据

According with the official documentation, you must call the session_start() method in each one of pages where you are going to use the session, so try to call session_start() in your index.php.

此方法开始新的会话或恢复现有会话,还检查与AJAX请求一起发送的与您的index.php PHPSESSID匹配的PHPSESSID cookie.

This method starts new or resumes existing session, also check your PHPSESSID cookie sent with the AJAX request that match with your index.php PHPSESSID.

这篇关于php会话无法与ajax一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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