Laravel控制器:AJAX将请求数据放置在请求内容中

时间:2019-12-22 05:43:23

标签: jquery ajax laravel

我正在向我的 ItemController 发送POST请求,该请求通过并可以生成响应。但是我无法提取AJAX请求传递的数据。

以下是片段脚本/刀片模板的内容: layout.blade.php

<script>
$("#ajaxRequest").click(
    function(){
        $.ajax({
            url: '/itemAjaxReq',
            type: 'POST',
            dataType: 'html',
            contentType:'application/json',
            headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            data: 
            { 
                data1: 'ABC', 
                data2: 'DEF'                       
            },
            error: function() {alert('Error');},
            success: function(response) {                                                    
                        $('#ajaxResponse').empty();
                        $('#ajaxResponse').append(response);
                    }
    });
</script>

<div>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <button id="ajaxRequest">Test ajax request</button>
</div>

<div id="ajaxResponse">
</div>

路由: web.php

Route::post('itemAjaxReq','ItemController@ajaxReq')->name('items.ajaxReq');

模型: ItemController.php     

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;
use Illuminate\Validation\Rule;

class ItemController extends Controller
{   
    //... some skipped functions
    public function ajaxReq()
    {
        if(request()->ajax())
        {
            \error_log("This is an AJAX Request");
            //dd(request());
            $data = request()->all();
            //dd($data);
            \error_log("Request :\n" . request() . "\n");
            \error_log("data1 : " . request()->input('data1'));
            \error_log("data2 : " . request()->data2);
            \error_log("data3 : " . request()->data3);
            return "Response :\n"."Some data here";
        }
    }
}

如果我取消注释dd($data),则会得到空数组([])。如果我取消注释dd(request()),那么数据将显示在受保护的变量#content上。这是代码段:

Illuminate\Http\Request {#51 ▼
  #json: Symfony\Component\HttpFoundation\ParameterBag {#43 ▶}
  #convertedFiles: null
  #userResolver: Closure($guard = null) {#31 ▶}
  #routeResolver: Closure() {#253 ▶}
  +attributes: Symfony\Component\HttpFoundation\ParameterBag {#53 ▶}
  +request: Symfony\Component\HttpFoundation\ParameterBag {#43 ▶}
  +query: Symfony\Component\HttpFoundation\ParameterBag {#59 ▶}
  +server: Symfony\Component\HttpFoundation\ServerBag {#55 ▶}
  +files: Symfony\Component\HttpFoundation\FileBag {#56 ▶}
  +cookies: Symfony\Component\HttpFoundation\ParameterBag {#54 ▶}
  +headers: Symfony\Component\HttpFoundation\HeaderBag {#57 ▶}
  #content: "data1=ABC&data2=DEF"
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: "/itemAjaxReq"
  #requestUri: "/itemAjaxReq"
  #baseUrl: ""
  #basePath: null
  #method: "POST"
  #format: null
  #session: Illuminate\Session\Store {#273 ▶}
  #locale: null
  #defaultLocale: "en"
  -preferredFormat: null
  -isHostValid: true
  -isForwardedValid: true
  basePath: ""
  format: "html"
}

如果我扩展+attributes+request+query属性,那么我将获得#parameters: []

传递数据时我是否犯了错误?如何从content属性中提取它?

3 个答案:

答案 0 :(得分:0)

对于Laravel> = 5.5,您只需致电

$request->post() or $request->post('my_param')

内部调用

$request->request->all() or $request->request->get('my_param')

分别。

希望有帮助。

答案 1 :(得分:0)

将此代码写入您的控制器中。

public function ajaxReq(Request $request)

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;
use Illuminate\Validation\Rule;

class ItemController extends Controller
{   
    //... some skipped functions
    public function ajaxReq(Request $request)  // pass request param
    {


            $data = $request->all()
            dd($data);
            exit();

            return "Response :\n"."Some data here";

    }
}

答案 2 :(得分:0)

好的,我已经解决了这个问题。但是我不明白为什么该解决方案有效。

我将AJAX请求contentTypecontentType:'application/json'更改为contentType:'application/x-www-form-urlencoded'

问题不在于不使用$request,也不是通过->post('data1')->input('data1')来获取。使用request()或通过->data1直接获取它都可以。