12. Lấy giá trị JSON input (Retrieving JSON input value) (ok)
https://viblo.asia/p/tap-16-request-laravel-aWj534Y8K6m
Chẳng hạn chúng ta có blade view form
như sau:
<form action="/post" method="POST">
@csrf
<div>
<button type="submit">Submit</button>
</div>
</form>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script>
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
url: '/post',
type: 'POST',
data: {
_token: $('input[name=_token]').val(),
user: {
name: 'Lê Chí Huy',
age: 18
}
}, success: function(res) {
console.log(res);
}
});
});
</script>
Như đoạn code trên thì sau khi click "Submit", chúng ta sẽ thực thi ajax đã gửi request có kèm data json user
tới controller.
Tại controller FormController
, để tham chiếu data json user
này, ta thực hiện như sau:
public function post(Request $request)
{
return $request->input('user.name');
}
Chúng ta tham chiếu đến các phần tử trong JSOn như là array input ở phần trên.
Previous11. Lấy dữ liệu input thông qua thuộc tính động (Retrieving input via dynamic properties) (ok)Next13. Lấy một phần dữ liệu input (Retrieving a portion of input data)
Last updated
Was this helpful?