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

标签 javascript jquery ajax json laravel-5

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/

相关文章:

javascript - 为什么 JavaScript ES6 不支持多构造类?

jquery - 欺骗 ASP.NET 认为请求是 jQuery 文件上传的 Ajax 请求

javascript - JQuery、谷歌地图和 $ ('#myId' ) == getElementById ("myId")

jQuery:仅显示从当前 View 可见的内容并在滚动时加载其余内容

javascript - 每次加载ajax或一次加载所有内容

javascript - 使用 Spring MVC 自动刷新对象的一些属性

javascript - 将二维数组从 PHP 转换为 JS

json - Elasticsearch不返回jsonp

javascript - 提交时出现问题 - 更新

javascript - JavaScript 新手,如何进行 null 检查?