![](/img/trans.png)
[英]Pass data from controller to view using JQuery Ajax in Laravel 5.4
[英]laravel pass data from controller to jquery using json
我想使用json將數據從控制器傳遞到jquery,不知道問題出在哪里,但是在jquery代碼中,我認為它在我測試成功代碼時可以正常工作,但無法從controller取回結果
刀片
<form role="form" name="form_address" id="form_address" action="" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" id="postal_code" onFocus="geolocate()">
<input type="text" id="totaldistance" onFocus="geolocate()">
</form>
<button id="save_address">Save</button>
<script>
$("#save_address").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
e.preventDefault();
var form = document.forms.namedItem("form_address");
var formData = new FormData(form);
$.ajax({
type: "get",
url: 'Get_distance',
contentType: false,
data: formData,
processData: false,
success: function(data) {
$('#totaldistance').val(data.distance);
}
});
});
web.php
Route::post('Get_distance','HomeController@getdistance');
控制者
public function getdistance(Request $request)
{
$distance =$request->postal_code;
return Response::json(array(
'distance' => $distance,
));
}
將您的ajax類型更改為POST
,因為您的路由類型是POST
而不是GET
。
您在web.php中定義的路由是POST請求,但是您的Ajax方法設置為GET請求。 將web.php更改為GET請求以使其正常工作。 確保提供錯誤功能以捕獲服務器端的所有錯誤。
反之亦然,因為您已經添加了csrf設置,所以將Ajax請求更改為POST。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.