简体   繁体   English

Laravel Controller:AJAX post 请求数据放置在请求内容中

[英]Laravel Controller: AJAX post request data placed in request content

I'm sending a POST request to my ItemController , the request came through and the response can be generated.我正在向我的ItemController发送一个 POST 请求,请求通过并且可以生成响应。 But I am unable to extract the data passed by the AJAX request.但是我无法提取 AJAX 请求传递的数据。

Here's a snippet script/blade template content: layout.blade.php :这是一个片段脚本/刀片模板内容: 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>

Route: web.php路径web.php

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

Model: ItemController.php型号: 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";
        }
    }
}

If I uncomment the dd($data) , I got empty array ( [] ).如果我取消注释dd($data) ,我会得到空数组 ( [] )。 If I uncomment the dd(request()) , then the data appear on the protected variable #content .如果我取消注释dd(request()) ,那么数据会出现在受保护的变量#content Here's the snippet:这是片段:

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

If I expanded +attributes , +request , and +query properties, I got #parameters: []如果我展开+attributes+request+query属性,我会得到#parameters: []

Did I make mistake when passing the data?我在传递数据时出错了吗? How do I extract it from the content attribute?如何从内容属性中提取它?

For Laravel >= 5.5, you can simply call对于 Laravel >= 5.5,你可以简单地调用

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

which internally calls内部调用

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

respectively.分别。

Hope it helps.希望能帮助到你。

OK, I've solved the issue.好的,我已经解决了这个问题。 But I don't understand why the solution works.但我不明白为什么该解决方案有效。

I changed the AJAX request contentType from contentType:'application/json' to contentType:'application/x-www-form-urlencoded'我将 AJAX 请求contentTypecontentType:'application/json'更改为contentType:'application/x-www-form-urlencoded'

The problem isn't on using not using $request , nor fetching it via ->post('data1') or ->input('data1') .问题不在于不使用$request ,也不在于通过->post('data1')->input('data1')获取它。 Using request() or directly fetching it by ->data1 works fine.使用request()或直接通过->data1获取它可以正常工作。

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

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