AJAX 补丁请求在 Laravel 控制器中返回空

问题描述 投票:0回答:1

我正在尝试更新 Laravel 中的资源,并向我的控制器发送 PATCH 请求。 这是我的 AJAX 调用

    $.ajax('profile', { // Replace with your actual endpoint URL
    type: 'PATCH',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'), // CSRF token for Laravel
        // 'X-HTTP-Method-Override': 'PATCH'
    },
    data:  {status: 'some status'},
    success: function (data) {
        console.log(data);
    },
})
    .catch((error) => {
        console.error('Error:', error);
    });

目前我的控制器只是返回请求数据作为响应

public function update(ProfileUpdateRequest $request)
{
 return response()->json(['message' => 'Data updated successfully', 'data' => $request->all()]);
}

我收到消息“数据已成功更新”,但是数据数组完全为空。

我已经尝试过使用 type: 'POST' 并使用 _method: 'PATCH' 欺骗数据数组中的方法,这导致了消息“'POST' 不是此路由支持的方法。”

有什么想法吗?

编辑: 配置文件更新请求类:

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ProfileUpdateRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        return [
//            'name' => ['required', 'string', 'max:255'],
//            'email' => ['required', 'string', 'email', 'max:255'],
        ];
    }
}
json ajax laravel
1个回答
0
投票

当您设置 *'Content-Type': 'application/json' 时,您必须显式发送 json 编码数据:

$.ajax("profile", {

    method: 'PATCH',  // method is used instead of type in latest versions of JQuery
    contentType:'application/json', // there is an option to set 'Content-Type' without using headers
    headers: {
        "X-CSRF-TOKEN": "{{ csrf_token() }}" // this may be a more concise option for CSRF-TOKEN
    },

    data: '{"status": "some status"}',  // or if you prefer: JSON.stringify ({status: "some status"})

    .....

但是在您的 ProfileUpdateRequest 中,您必须手动提取数据:

class ProfileUpdateRequest extends FormRequest
{
    .....

    protected function prepareForValidation()
    {
        $this->merge(json_decode($this->getContent(), associative: true));
    }

    .....

我的建议是在请求中保留默认的contentTypeapplication/x-www-form-urlencoded; charset=UTF-8)并更简单地继续:

$.ajax("profile", {

    method: 'PATCH',

    headers: {
        "X-CSRF-TOKEN": "{{ csrf_token() }}"
    },

    data: {status: "some status"},
    
    .....

这样

return response()->json(['message' => 'Data updated successfully', 'data' => $request->all()]);
将提供预期的结果

© www.soinside.com 2019 - 2024. All rights reserved.