繁体   English   中英

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

laravel 5.3使用的最简单方法

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

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

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

我有同样的问题。 我用echo json_encode($result); 语句,然后将其替换为return json_encode($result); 声明,它就像魅力。

暂无
暂无

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

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