Метод GET не поддерживается для этого маршрута. Поддерживаемые методы: POST. Ларавел 5.8 Аякс - PullRequest
6 голосов
/ 21 марта 2019

Я пытаюсь понять больше о том, как сохранить данные из запроса ajax в базу данных на laravel. Данные в этом случае являются необработанными (JSON FORMATTED) данными, просто чтобы посмотреть, как это работает, работает нормально, если я не добавлю это вкод (обратите внимание на сохранение в базе данных)

часть сохранения

 $input = Input::get('name');
 $json = new JsonTest;
 $json->json = $input;
 $json->save();

работает нормально, но когда у меня есть эта часть сверху в коде (часть сохранения), это даетошибка

   The GET method is not supported for this route. Supported methods: POST.

, так как я могу сохранить текстовую область в базу данных.база данных база данных

web.php

 Route::post('/customer/ajaxupdate', 'AjaxController@updateCustomerRecord')- 
 >name('jsonTest');

Контроллер

public function updateCustomerRecord(Request $request)
{

    if(request()->ajax()){

        $input = Input::get('name');
        //$input = $request->all();
        $json = new JsonTest;
        $json->json = $input;
        $json->save();

        return response()->json(['status' => 'succes', 'message' => 'saved in database']);

    } else {

        return response()->json(['status' => 'fail', 'message' => 'this is not json']);

    }

}

Клинок

 <!DOCTYPE html>
 <html lang="en">
<head>
<title>JavaScript - read JSON from URL</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>

<body>
<textarea  oninput="myFunction()" id="input" name="input" style="height: 
500px;width: 500px">
</textarea>

<script>
const warning = 'This json is not correctly formatted';
const text = {status: "failed", message: "this is not correct json format"};

$.ajaxSetup({
    headers: {

        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

    }
});

function myFunction(){

    let input = document.getElementById("input").value;

    try {
        let id = JSON.parse(input);
        if (id && typeof id === "object") {
            $.ajax({
                method: 'POST', // Type of response and matches what we said in the route
                url: '{{ route('jsonTest') }}', // This is the url we gave in the route
                data: {'id' : id}, // a JSON object to send back
                success: function(response){ // What to do if we succeed
                    console.log(response);
                },
                error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
                    console.log(JSON.stringify(jqXHR));
                    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                }
            });
        }
    }
    catch (e) {
        console.log(warning);
        console.log(text);
    }
    return false;
}
</script>

</body>
</html>

1 Ответ

2 голосов
/ 22 марта 2019

Похоже, вы не включили ключ name в свои данные POST.Попробуйте это:

$.ajax({
    method: 'POST', // Type of response and matches what we said in the route
    url: '{{ route('jsonTest') }}', // This is the url we gave in the route
    data: {'name' : 'testing'}, // <-- this is your POST data
    success: function(response){ // What to do if we succeed
        console.log(response);
    },
    error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
        console.log(JSON.stringify(jqXHR));
        console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...