【问题标题】:Laravel Controller: AJAX post request data placed in request contentLaravel Controller:AJAX 发布请求数据放在请求内容中
【发布时间】:2019-12-22 05:43:23
【问题描述】:

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

这是一个 sn-p 脚本/刀片模板内容: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 上。这是sn-p:

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: []

我在传递数据时犯错了吗?如何从内容属性中提取它?

【问题讨论】:

    标签: jquery ajax laravel


    【解决方案1】:

    对于 Laravel >= 5.5,你可以简单地调用

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

    内部调用

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

    分别。

    希望对你有帮助。

    【讨论】:

    • 试图打印出request()-&gt;post()500 Internal server error
    • 检查服务器日志。
    • 它说:local.ERROR: Array to string conversion {"exception":"[object] (ErrorException(code: 0): Array to string conversion at D:\\xampp\\htdocs\\laravelmongodb\\app\\Http\\Controllers\\ItemController.php:129) 第 129 行是我打印请求的地方:\error_log("Request :\n" . request()-&gt;post() . "\n");
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      相关资源
      最近更新 更多