我正在尝试在 Laravel 中发出 AJAX 请求,但它给了我错误“422(无法处理的内容)”

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

我正在尝试使用 AJAX 请求进行 CRUD。我可以显示数据库中的数据。但是当我尝试向其中添加数据时,它给了我错误 “此路由不支持 POST 方法。支持的方法:GET、HEAD”。 给我一个解决方案。我只是 laravel 的新手。

这是我的 web.php

Route::get('projects',[ProjectController::class, 'index']) -> name('projects.index');
    Route::get('project-list', [projectController::class, 'list']);
    Route::post('project-add', [projectController::class, 'store']);
    Route::get('project-view', [projectController::class, 'show']);
    Route::get('project-delete', [projectController::class, 'destroy']);
    Route::post('project-edit', [projectController::class, 'update']);

这是我在控制器(ProjectController)中的存储功能

public function store(ProjectStoreRequest $request)
    {
        $deadline = Carbon::parse($request->deadline)->format('Y-m-d');
        $project = [
            'title' => $request->title,
            'description'=> $request->description,
            'deadline' => $deadline,
            'status' => $request->status,
            'client_id' => $request->client_id,
        ];
        $data = Project::create($project);
        if($data){
            $response = [
                'status'=>'ok',
                'success'=>true,
                'message'=>'Record created succesfully!'
            ];
            return $response;
        }else{
            $response = [
                'status'=>'ok',
                'success'=>false,
                'message'=>'Record created failed!'
            ];
            return $response;
        }

}

这是我的刀片文件

@extends('layouts.admin')

@section('content')
    <div class="content-wrapper">
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1>Projects</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            @can('projects.write')
                                <li class="breadcrumb-item"><a href="javascript:void(0)" data-bs-toggle = "modal" data-bs-target="#exampleModal" class = "btn btn-primary" id = "create"><i
                                            class="fas fa-plus-circle"></i></a></li>
                            @endcan
                        </ol>
                    </div>
                </div>
            </div>
        </section>
        <div class="row justify-content-center">
            <div class="card-body">
                @if (session('success'))
                    <div class="alert alert-success" role="alert">
                        {{ session('success') }}
                    </div>
                @endif
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>S.No</th>
                        <th>Title</th>
                        <th>Description</th>
                        <th>Client Name</th>
                        <th>Deadline</th>
                        <th>Status</th>
                        <th colspan="2">Action</th>
                    </tr>
                    </thead>
                    <tbody class = "projectdata">
                    {{-- @php
                        // get current page for Paginator
                        $currentPage = (\Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage() - 1) * 10;
                    @endphp
                    @foreach($projects as $key => $project)
                        <tr>
                            <td>{{ $currentPage + $key + 1 }}</td>
                            <td>{{ $project->title }}</td>
                            <td>{{ $project->description }}</td>
                            <td>{{ $project->client->name ?? '-' }}</td>
                            <td>{{ \Carbon\Carbon::parse($project->deadline)->format('Y-m-d') ?? '-' }}</td>
                            <td>{{ $project->status }}</td>
                             <td>
                                @canany(['projects.write', 'projects.read'])
                                    <a href="{{ route('projects.show', $project->id) }}" class="btn btn-primary">Show</a>
                                @endcan
                                @can('projects.write')
                                    <a href="{{ route('projects.edit', $project->id) }}" class="btn btn-primary">Edit</a>
                                    <form action="{{ route('projects.destroy', $project->id) }}" method="post" class="d-inline">
                                        {{ csrf_field() }}
                                        @method('DELETE')
                                        <button class="btn btn-danger" type="submit">Delete</button>
                                    </form>
                                @endcan
                            </td>
                        </tr>
                    @endforeach --}}
                    </tbody>
                </table>
                {{-- <div style="margin-top: 10px;">
                    {{ $projects->links('pagination::bootstrap-4') }}
                </div> --}}
            </div>
        </div>
    </div>
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            </div>
            <div class="modal-body">
                <div class="card-body">
                    <form action="" method="POST">
                        <input type="hidden" name="_token" id = "csrf" value="{{ csrf_token() }}" />
                        <div class="form-group">
                            <label for="">Title</label>
                            <input type="text" name="title" id = "title" class="form-control">
                            @if ($errors->has('title'))
                                <div class="text-danger" style="margin-top: 10px; margin-bottom: 10px;">{{ $errors->first('title') }}</div>
                            @endif
                        </div>
                        <div class="form-group">
                            <label for="">Description</label>
                            <textarea name="description" id = "description" rows="5" cols="10" class="form-control"></textarea>
                            @if ($errors->has('description'))
                                <div class="text-danger" style="margin-top: 10px; margin-bottom: 10px;">{{ $errors->first('description') }}</div>
                            @endif
                        </div>
                        <div class="form-group">
                            <label>Deadline:</label>
                            <div class="input-group date" id="deadline" data-target-input="nearest">
                                <input type="date" id = "deadline" name="deadline" class="form-control" data-target="#deadline"/>
                            </div>
                            @if ($errors->has('deadline'))
                                <div class="text-danger" style="margin-top: 10px; margin-bottom: 10px;">{{ $errors->first('deadline') }}</div>
                            @endif
                        </div>
                        <div class="form-group">
                            <label for="">Status</label>
                            <select class="form-control" name="status" id="status">
                                <option value="Proposal">Proposal</option>
                                <option value="In Progress">In Progress</option>
                                <option value="Completed">Completed</option>
                            </select>
                            @if ($errors->has('status'))
                                <div class="text-danger"
                                     style="margin-top: 10px; margin-bottom: 10px;">{{ $errors->first('status') }}</div>
                            @endif
                        </div>
                        <div class="form-group">
                            <label for="">Select Client</label>
                            <select class="form-control" name="client_id" id="clients_list">
                                @foreach($clientUsers as $client)
                                    <option value="{{ $client->id }}">{{ $client->name }}</option>
                                @endforeach
                            </select>
                            @if ($errors->has('client_id'))
                                <div class="text-danger"
                                     style="margin-top: 10px; margin-bottom: 10px;">{{ $errors->first('client_id') }}</div>
                            @endif
                        </div>
                        <div style="margin-top: 20px;">
                            <a href="javascript:void(0)" data-bs-dismiss="modal" class="btn btn-primary">Cancel</a>
                            <a href = "javascript:void(0)" class = "btn btn-primary" id = "save">Add</a>
                        </div>
                    </form>
                </div>
            </div>
          </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function() {
            projects();
        });
        function projects(){
            $.ajax({
                type : 'get',
                url : "{{url('project-list')}}",
                success : function(response) {
                    console.log(response);
                    var tr = '';
                    for(var i = 0;i<response.length;i++){
                        var title = response[i].title;
                        var description = response[i].description;
                        var clientname = response[i].client.name;
                        var deadline = response[i].deadline;
                        var status = response[i].status;
                        tr += '<tr>';
                        tr += '<td>' + (i+1) + '</td>';
                        tr += '<td>' +title + '</td>';
                        tr += '<td>' + description + '</td>';
                        tr += '<td>' + clientname + '</td>';
                        tr += '<td>' + deadline + '</td>';
                        tr += '<td>' + status + '</td>';
                        tr += '<td><div class = "justify-content-around">'
                        tr += '<a href = "javascript:void(0)" class = "btn btn-primary">Show</a>'
                        tr += '<a href = "javascript:void(0)" class = "btn btn-primary">Edit</a>'
                        tr += '<a href = "javascript:void(0)" class = "btn btn-danger">Delete</a>'
                        tr += '</div></td>'
                    }
                    console.log(tr);
                    $('.projectdata').html(tr);
                }
            });
        }
$('#save').click(function(){
            addProject();
});
        

function addProject(){
            var title = $('#title').val();
            var description = $('#description').val();
            var deadline = $('#deadline').val();
            var status = $('#status').val();
            var client = $('#clients_list').val();
            var token = $('#csrf').val();
            console.log(client);
            $.ajax({
                type: 'post',
                data: {
                    title: title,
                    description: description,
                    deadline: deadline,
                    status: status,
                    client_id: client,
                    _token: token
                },
                url: "{{ url('project-add') }}",
                success: function(response) {
                    $('#exampleModal').modal('hide');
                    projects();
                    alert(response.message);
                }
            });
        }
    </script>
@endsection

正如评论中给出的,我没有首先调用 addProject() 函数。是我的疏忽,我很抱歉。但现在当我运行它时,它给了我以下错误

Failed to load resource: the server responded with a status of 422 (Unprocessable Content)
php ajax laravel routes crud
1个回答
-1
投票

您可以指定“这条”路线。像这样设置你的路线:

Route::delete('project-delete', [projectController::class, 'destroy']);

希望对你有帮助,否则可以具体说明吗,谢谢。

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