我是“AJAX”的新手,我一直在尝试使用“AJAX”发送请求“ONSELECT”并在“laravel 5”中收到“JSON”响应。
这是我的看法
<select>
<option data-id="a" value="a">a</option>
<option data-id="b" value="b">b</option>
<option data-id="c" value="c">c</option>
</select>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
$('select').change(function(){
var data = $(this).children('option:selected').data('id');
$.ajax({
type :"POST",
url :"http://localhost/laravel/public/form-data",
dataType:"html",
data :{ data1:data },
success :function(response)
alert("thank u");
}),
});
</script>
这是我的 Controller 接收ajax请求
public function formdata(){
$data = Input::get('data1');
//somecodes
return Response::json(array(
'success' => true,
'data' => $data
));
}
这是我的路线
Route::post('form-data',array('as'=>'form-data','uses'=>'FormController@formdata'));
我也曾尝试仅使用 form-data
和 {{Url::route('form-data')}}
来更改 ajax 的 URL。
最佳答案
出于安全原因,Laravel 5 使用 csrf token 验证....试试这个...
在 routes.php 中
route post('form-data', 'FormController@postform');
在主布局文件中
<meta name="csrf-token" content="{{ csrf_token() }}" />
-
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({ url: '/form-data/', type: 'POST', data: {_token: CSRF_TOKEN}, dataType: 'JSON', success: function (data) { console.log(data); } });
关于javascript - 在 Laravel 5 中使用 Ajax 并返回 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28599638/