Laravel 5.0 ajax请求保存会话变量


Laravel 5.0 ajax request to save session variable

我正试图使用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.');
        }
    }
}

有人知道为什么这似乎拒绝实际保存会话变量吗?我在某个地方读到,这可能与会话状态有关,然而,我一直未能找到解决方案的提示。

编辑:这是我的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();
}

以下是页面上的按钮:

<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>

最后,这里是我的路线:

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

谢谢。

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

routes.php

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

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'
      });
  });

如果你愿意的话,你可以将其规范化一点,并返回一个值,这样你就可以看到发生了什么。

routes.php

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

控制器

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']); 
}

编辑每个更新的问题

您需要将X-Requested-With标头添加到XMLHttpRequest中。

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

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

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();
}

您可能需要查看jQuery。它为JavaScript增加了一点体积,但处理起来要容易得多。

你可以这样写你的方法。

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

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

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

我也有同样的问题。我使用了echo json_encode($result);语句,然后用返回json_encode($result);语句替换了它,它的工作方式很有魅力。

laravel 5.3中使用的最简单方法

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