Как уже говорилось, это не ответ на ваш вопрос, а простое объяснение, которое вы задали в комментариях.И это может помочь кому-то еще
Laravel and JQuery
Насколько мощным: -)
Сначала я постараюсь максимально приспособить это к вашим потребностям с помощью информации, которую вы
Во-вторых, jquery содержит несколько классных функций для задниц, о которых многие люди не знают.
Как вы описали, у вас есть одностраничный веб-сайт или что-то в этом роде.Это означает, что у вас есть 1 route
, чтобы показать одну страницу, которую я предлагаю /take-stats/{{$game->id}}
.В вашем контроллере и в качестве примера я использую GameController
, у вас есть что-то вроде следующего.
class GameController
{
public function __construct()
{
}
//the single page view
public function index()
{
//your singlepage logic here....
return view('games.index'); //something like this?
}
public function create() //this is where you post to
{
//logic to store the game stats...
//this is where you return a succes message or something.
//lets return the index instead :-)
//dont't return $this->index! use redirect to the route.
return redirect()->route('the.route.to.your.index');
}
}
Как вы видите выше, мы возвращаем одну страницу в ответном сообщении.SSo, когда вы публикуете метод store, и он успешно выполняется, он возвращает страницу индекса.
Теперь jquery.
$('input#addStatButton').on( function() {
//this is where to do the post.
$.post(`{{ route('to.your.store.route') }}`, $('form#new_stat').serialize(), (response) => {
//clear the stats because the post is succeeded in here
//also reload the content. The response contains the new html content
//now what we can do is replace the whole content....
//something like $(`html`).html('response);
//or we get the content we need from the response and this is where jquery comes in handy. The response is simply a html response so jquery can create a new dom from it.
let statsList = $(response).find(`#statslist`).html(); //create a dom element of the response.
$(`#statslist`).html(statslist); //put the filtered html in the current list.
//thats all :-)
}).fail(() => {
// a fail save. When the post fails it will come in here.
}).always(() => {
clearStats();
//this is called always even when it fails. You can clear the stats or something in here.
});
});
Краткое описание:
- Нажмите кнопку «Отправить», отправьте сообщение на
post.route
- Метод контроллера выполняет логику и возвращает в качестве успеха индексный URL.
- jquery анализирует HTML-ответ и заменяет исходное содержимое.
- готово.
Надеюсь, это поможет вам или кому-то еще.При использовании структуры, подобной приведенной выше, этот код становится чище и быстрее, поскольку он выполняет только один запрос.