【发布时间】:2023-02-25 04:43:26
【问题描述】:
我试图在控制器内部获取请求数据,但 Laravel 没有显示任何内容。在其他控制器中使用得到方法我可以轻松做到。
在这种情况下我不能使用页面重定向,所以 Ajax 是我唯一的选择。
我搜索了整个 stackoverflow,但找不到任何有用的东西。
我的代码:
web.php
Route::post('adiciona_credito', [AdicionaCreditoController::class, 'post_credito'])->name('adiciona_credito.post');
AdicionaCreditoController.php
<?php
namespace App\Http\Controllers\MixVirtual;
use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Http\Request;
class AdicionaCreditoController extends Controller {
public function post_credito(Request $request): array {
dd(request()->all()); // print the request
try {
// Saving data to the database.
$retorno['msg'] = 'success';
}
catch (Exception $e) {
$retorno['msg'] = $e->getMessage();
}
header('Content-type: application/json;charset=utf-8');
return $retorno;
}
}
ajax.js
document.getElementById('form_adiciona_credito').addEventListener('submit', function(event) {
event.preventDefault();
let headers = new Headers();
headers.append('X-CSRF-TOKEN', document.querySelector('[name="csrf-token"]').getAttribute('content'));
let options = {
method : 'POST',
headers: headers,
body : JSON.stringify({
credito : document.getElementById('credito').value,
justificativa: document.getElementById('justificativa').value
})
}
fetch('./adiciona_credito', options).then(function(response) {
if (!response.ok) {
// Treating errors
}
response.json().then(function(return) {
// AJAX callback
});
});
}
HTML表格
<form id="form_adiciona_credito" method="post" action="{{route('adiciona_credito.post')}}">
@csrf
<div class="row">
<div class="col-12 my-1">
<input required type="number" class="form-control" id="credito" placeholder="Crédito para adicionar">
</div>
<div class="col-12 my-1">
<textarea required class="form-control" id="justificativa" placeholder="Justificativa"></textarea>
</div>
<div class="col-12 my-1">
<button class="btn btn-success float-end" id="btn_adiciona_credito">Add
</button>
</div>
</div>
</form>
【问题讨论】:
-
你在你的控制器中尝试过
return response()->json($retorno);吗? -
我自己不使用
fetch()方法,但如果您要发送body: JSON.stringify(),那么如果您还将contentType标头设置为application/json,那么$request->all()可能会起作用。或者试试application/x-www-form-urlencoded和body: {credito: ..., justificativa: ...}。在将 Laravel 用作 API 时,您不必使用request()->getContent(),而是更多地处理您的请求,看看您是否可以让$request->all()和$request->input('credito')工作。
标签: php ajax laravel forms request