如果 AJAX 请求是 "pure content" 那么其他参数来自哪里?

If an AJAX request is "pure content" then where are the other parameters coming from?

我不是专家,但是当我进行 AJAX 调用时,我希望收到(服务器端)我放入 data 参数的确切内容 AJAX 呼叫。

这正是我在 chrome 开发控制台 > 网络中看到的。

服务器端,我很难访问这些数据。 首先,gettype() 告诉我我正在接收一个对象,但它看起来像一个数组。

其次,如果我将它转换为数组,所有其他垃圾都会被添加进来。

一个简单的 Log::info($AJAXRequest) 显示我收到了一个数组。

[2018-08-24 02:14:15] local.INFO: array (
  0 => 
  array (
    'category' => 'xyz',
    array (
      0 => 
      ... etc. 

$arr = (array) $AJAXrequest; 之后,一个简单的 Log::info($arr); 显示我有一个数组,前面添加了各种其他垃圾。

[2018-08-24 02:14:15] local.INFO: array (
  '' . "[=13=]" . '*' . "[=13=]" . 'json' => 
  Symfony\Component\HttpFoundation\ParameterBag::__set_state(array(
     'parameters' => 
    array (
      0 => 
      array (
        'category' => 'xyz',
        array (
          0 => 
        ... etc. 

这些额外的内容从何而来?我只是试图将我认为是一个对象的东西转换成一个数组。

AJAX 调用 Javascript:

 $.ajax({
      type:"POST",
      url:"/surveys",
      contentType: "application/json; charset=utf-8",
      headers: {
        'CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      data: JSON.stringify(data),
      dataType: 'html',
      success: function(data){alert("Success");},
      failure: function(errMsg) {alert("Fail");}        
    });
    }

资源控制器

...
 public function store(Request $AJAXrequest)
...
  if($AJAXrequest->ajax()){
            $arr = (array) $AJAXrequest;
            Log::info(gettype($AJAXrequest));
            Log::info(gettype($arr));
 .....

我认为最好向后工作以帮助您消除误解...

Laravel 的 Illuminate\Log\Logger class 通过内部方法 formatMessage() 运行所有日志消息,其中包括

if ($message instanceof Arrayable) {
    return var_export($message->toArray(), true);
}

现在,Request implements Arrayable so it satisfies this condition, calling the toArray()方法

/**
 * Get all of the input and files for the request.
 *
 * @return array
 */
public function toArray()
{
    return $this->all();
}

这就是为什么您会看到自己为 Log::info($AJAXrequest)

所做的事情

现在,如果您刚好在反序列化 JSON 之后,那应该可以在

中找到
$AJAXRequest->json()

哪个 returns 一个 ParameterBag 实例。

如果您在发布的 JSON 字符串之后,请使用

$AJAXrequest->getContent()