Laravel 5.0 ajax 请求保存会话变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33487448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:37:22  来源:igfitidea点击:

Laravel 5.0 ajax request to save session variable

phpajaxsessionlaravel

提问by Logan Hasbrouck

I am attempting to use an ajax request to save a session variable which is used to disable my site's background images. As of right now, it DOES work if I simply go to the route itself, however, if I run the function through an ajax request, it fails completely and does NOT save the value to session even if it shows it in the dd(Session::all())right after.

我正在尝试使用 ajax 请求来保存用于禁用我网站的背景图像的会话变量。截至目前,如果我只是转到路由本身,它确实可以工作,但是,如果我通过 ajax 请求运行该函数,它会完全失败并且不会将值保存到会话,即使它在dd(Session::all())之后显示它。

<?php namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Session;
use Request;
use App;
use Response;

class SessionVarController extends Controller {

    public function backgroundImgsOff()
    {
        if(Request::ajax())
        {
            Session::put(['backgroundImgDisable' => true]);
            return Response::json(); 
        }
        else
        {
            App::abort(404, 'Page not found.');
        }
    }

    public function backgroundImgsOn()
    {
        if(Request::ajax())
        {
            Session::forget(['backgroundImgDisable']);
            return Response::json(); 
        }
        else
        {
            App::abort(404, 'Page not found.');
        }
    }

}

Does anyone know why this seems to refuse to actually save the session variable? I read somewhere that it may have to do with session states, however, I have been unsuccessful in locating so much as a hint to a solution.

有谁知道为什么这似乎拒绝实际保存会话变量?我在某处读到它可能与会话状态有关,但是,我没有成功找到解决方案的提示。

EDIT: here is my ajax (keep in mind this is my first attempt at ajax).

编辑:这是我的 ajax(请记住,这是我第一次尝试 ajax)。

function enableBackgroundImages() {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","{{ action('SessionVarController@backgroundImgsOn') }}",true);
    xmlhttp.send();
}
function disableBackgroundImages() {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","{{ action('SessionVarController@backgroundImgsOff') }}",true);
    xmlhttp.send();
}

Here are the buttons on the page:

以下是页面上的按钮:

<div id="background-on-off" style="display:inline-block;">
    Background Images: 
    <a href="#" onClick="enableBackgroundImages();">
        On
    </a>
    / 
    <a href="#" onClick="disableBackgroundImages();location.reload();">
        Off
    </a>
</div>

Lastly, here are my routes:

最后,这里是我的路线:

Route::get('background_images_on', 'SessionVarController@backgroundImgsOn');
Route::get('background_images_off', 'SessionVarController@backgroundImgsOff');

Thanks.

谢谢。

回答by whoacowboy

Your controller code works. It probably has to do with how your routes or your ajax call.

您的控制器代码有效。这可能与您的路由或 ajax 调用方式有关。

routes.php

路由文件

Route::post('background-imgs/disable','SessionVarController@backgroundImgsOff');
Route::post('background-imgs/enable','SessionVarController@backgroundImgsOn');

jQuery

jQuery

  $("#on").on('click', function () {
      var that = this;
      $.ajax({
          type: "POST",
          url:'/background-imgs/enable'
      });
  });

  $("#off").on('click', function () {
      var that = this;
      $.ajax({
          type: "POST",
          url:'/background-imgs/disable'
      });
  });

You could normalize this a bit if you wanted and return a value so you can see what's happening.

如果您愿意,您可以将其规范化并返回一个值,以便您可以看到发生了什么。

routes.php

路由文件

Route::post('background-imgs/{action}','SessionVarController@backgroundImages')
    ->where('action', '[enable]*[disable]*');

controller

控制器

class SessionVarController extends Controller {

public function backgroundImages($action = 'enable')
{
    if(!Request::ajax())
    {
        abort(404, 'Page not found.');
    }
    if ($action === 'enable'){
        Session::forget(['backgroundImgDisable']);
        return Response::json(['background' => 'enabled']); 
    }
    Session::put(['backgroundImgDisable' => true]);
    return Response::json(['background' => 'disabled']); 

}

Edit per updated question

编辑每个更新的问题

You need to add the X-Requested-Withheader to your XMLHttpRequest.

您需要将X-Requested-With标题添加到您的XMLHttpRequest.

Laravel uses Symfonyto check if it is an ajax request.

Laravel 使用Symfony来检查它是否是一个 ajax 请求。

public function isXmlHttpRequest()
{
    return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}

You javascript code should look like this.

你的 javascript 代码应该是这样的。

function enableBackgroundImages() {
  if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
  } else {
      // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET","{{ action('TestController@backgroundImgsOn') }}",true);
  xmlhttp.setRequestHeader('X-Requested-With','XMLHttpRequest');
  xmlhttp.send();
}
function disableBackgroundImages() {
  if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
  } else {
      // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET","{{ action('TestController@backgroundImgsOff') }}",true);
  xmlhttp.setRequestHeader('X-Requested-With','XMLHttpRequest');
  xmlhttp.send();
}

You might want to look into jQueryfor this. It adds a bit of bulk to your JavaScript but it is much easier to deal with.

您可能想为此研究jQuery。它为您的 JavaScript 增加了一些体积,但它更容易处理。

You could write your methods like this.

你可以这样写你的方法。

function enableBackgroundImages() {
        $.get("{{ action('SessionVarController@backgroundImgsOn') }}");
}
function disableBackgroundImages() {
        $.get("{{ action('SessionVarController@backgroundImgsOff') }}");
}

回答by Aman Jain

Easiest way in laravel 5.3 use

laravel 5.3 中最简单的使用方法

    \Session::put("userid",Input::get('userid'));
    \Session::save();

回答by Payal

You need to add following lines to return from ajax call and it will work like magic.

您需要添加以下行以从 ajax 调用返回,它会像魔术一样工作。

$result['status'] = 'success';
return json_encode($result);
exit;

I had the same problem. I used echo json_encode($result);statement and then I replaced it with return json_encode($result);statement and it works like charm.

我有同样的问题。我使用了echo json_encode($result);语句,然后用 returnjson_encode($result);语句替换了它,它的作用就像魅力一样。