简体   繁体   English

获取json数据并保存会话?

[英]Getting json data and saving session?

In my application, I am trying to do the login part where the user submits a form using POST to my own REST API which accepts the POST request. 在我的应用程序中,我尝试执行登录部分,其中用户使用POST向我自己的REST API提交表单,该REST API接受POST请求。

In my API I have set it to return a JSON object after extracting data from the database. 在我的API中,我已将其设置为从数据库提取数据后返回JSON对象。 I want this API to be used in an android application also to fetch JSON data so I can't redirect in the API code back to the home page. 我希望此API也可以在android应用程序中使用,以获取JSON数据,因此我无法将API代码重定向回首页。

How can I redirect back to the home page with the JSON object and save the session data before loading the home page? 如何在加载主页之前使用JSON对象重定向回主页并保存会话数据?

The home page should show in a corner that the user has logged in. 主页应显示在用户已登录的角落。

<form class = "form" action =<?php $_SERVER["DOCUMENT_ROOT"] ?> "/shades-api/get/login.php" method = "POST">
...
<button type="submit" name ="usignin" class="btn btn-success">Sign In</button>
</form>

API code API代码

header('Content-Type: application/json');
if(session_status() == PHP_SESSION_NONE){
  session_start();
}
require($_SERVER["DOCUMENT_ROOT"] .'/shades-api/services/userservice.php');
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
  if(isset($_POST['email']) && !is_null($_POST['email']) && trim($_POST['email']) != ""){
    if(isset($_POST['password']) && !is_null($_POST['password']) && trim($_POST['password']) != ""){

        $UserService = new Services\UserService();
        $json_obj = $UserService->login($_POST['email'], $_POST['password']);
      echo json_encode($json_obj);
    }
  }
}

you can use ajax if you are using REST API write below jquery this: 如果您使用的是REST API,则可以使用ajax在jquery下方编写以下代码:

<script>
$(document).ready(function() {
$(".form").submit(function(event) {
        event.preventDefault();
        var _form = $(this);
        var data = _form.serialize();
        var url = _form.attr('action');

        $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: "json",
            success: function(response) {
                        alert("Login successfully");
                       // write your redirect page
                        $('<a href="index.php" id="aa"></a>').appendTo("body");
                        document.getElementById("aa").click();                  


            },
            error: function() {}
        })
    });
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM