gpt4 book ai didi

javascript - 在 Laravel 5 中使用 Ajax 并返回 json 数组

转载 作者:可可西里 更新时间:2023-11-01 02:30:08 25 4
gpt4 key购买 nike

enter image description here我是“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 验证....试试这个...

  1. 在 routes.php 中

    route post('form-data', 'FormController@postform');
  2. 在主布局文件中

    <meta name="csrf-token" content="{{ csrf_token() }}" />
  3. 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com