php - ajax登录问题

标签 php javascript jquery ajax login-attempts

我创建了登录页面,它将 ajax 请求发送到 php 页面以进行登录验证。 在该 php 页面上,我正在创建 session ,并根据登录验证发送响应。 如果用户通过身份验证,我将其从发送ajax的java脚本重定向到主页。但在那个主页上我无法获取该 session 对象...为什么?你能告诉我在主页上检索该 session 的解决方案

最佳答案

我不确定我的做法是否正确,但这种方式对我有用(我希望我没有忘记任何事情):

这是我的login.php 的作用:

header('Content-type: text/json');

// here : import files I need

session_start();

// here : load some parameters into session variables
// here : init mysql connection
// here : get user and password from $_POST and check them against the database

// If the user can't connect, return an error to the client
if ( ! $ok )
{
    echo '{ "ok": "N" }';
    exit;
}

$_SESSION['user']    = $user;

echo '{ "ok": "O" }';

?>

然后,当我访问另一个 php 文件时,它是这样开始的:

header('Content-type: text/json');
// again, required files go here

session_start();

if ( ! isset($_SESSION['user'] )) {
        echo '{ "ok": "N" }';
    exit;
}

$user=$_SESSION['user'];
....

我进行的每个 ajax 调用都会检查结果是否告诉我用户未连接,如果没有连接,则返回到登录页面。

  $.ajax({
    type: "POST",
    url: "myphp.php",
    dataType: "json",
    data: somedatatopost,
    success: function(pRep){
      if (!pRep) {
        alert("No response from the server.");
        return;
      }
      if (pRep.ok=="N") {
        window.location = '/index.html';
        return;
      }
      // here is where I handle a successful response
    }
  });

对于登录ajax调用,我有:

[....]
// here is where I handle a successful response
window.location='mynewpage.html' 

关于php - ajax登录问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2452318/

相关文章:

javascript - var Foo = (function () { 等中的上下文

jquery - 如何使用 jquery 和 css vh 正确调整高度和宽度

javascript - 使用 JQuery 在 Asp.Net 中的页面回发之前调用函数

jquery - jQGrid Pager_left 宽度太小,列数少

php - 我需要哪个选项来使用 HHVM 编译 php 代码

php - Ajax 加载元标签

c# - Javascript ajax 调用无法访问我的 Web API Controller 页面。似乎无法获取正确的网址

javascript - 相当于 iText7 (.NET) 中的 stamper.addJavaScript 函数

php - 使用来自 php 的 Sql 查询进行数组操作以在 HTML 上显示它?

PHP:设置不同的值并使用 foreeach 和 mysql 选择