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