javascript - 在 Laravel 中通过 js onclick 事件提交数据

标签 javascript php laravel laravel-4

如何通过js的onclick事件提交表单?我正在使用 Laravel 4.1。

我试过这段代码

@foreach ($items as $item)
    <li>
        {{ Form::checkbox('items', $item->id , $item->done, ['onClick'=> 'this.form.submit()']) }}
        {{ $item->name }}
    </li>
@endforeach

但我得不到我想要的。 在 Controller 上我有以下代码:

public function postIndex()
{
    $id = Input::get('id');
    echo $id;
}

顺便说一句,在 chrome 控制台中我得到了以下错误:

Uncaught TypeError: Cannot read property 'submit' of null

谁能帮我解决这个问题?

最佳答案

据我所知,一个 View 中不应有多个标签。我建议你使用ajax 来触发提交事件。但是,您甚至没有一个表单打开标签,只有一个复选框。

我可能需要更多信息,但据我了解,您需要在单击复选框时向 Controller 提交数据。

我会这样做:

// Your view
<!-- CSRF Token -->
    <input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<!-- ./ csrf token -->

@foreach ($items as $item)
<input type="checkbox" name="{{$item->id}}" id="{{$item->id}}" value="{{$item->done}}" class="checkbox_click">
@endforeach

<script type="text/javascript">
    $(document).ready(function() {
        $('.checkbox_click').click(function(){                  
            var currentValue = $(this).attr("value");
            $.ajax({
                url: 'your/route',
                method: 'post',             
                data: {id: currentValue, _token: $('input[name="_token"]').val()},
                success: function(data){
                    alert(data);
                },
                error: function(){},
            });
        });         
    });
</script>

// Your controller
public function postIndex()
{
    if (Request::ajax)
    {
        $id = Input::get('id');

        return Response::json($id);
    }
}

// Your routes.php
Route::post('your/route', YourController@postIndex);

关于javascript - 在 Laravel 中通过 js onclick 事件提交数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234529/

相关文章:

javascript - (JavaScript) 将数据从较大的数组存储到具有其他关键属性的较小数组

javascript - Google map JavaScript 收费但隐藏在 CodeIgniter 上

php - Eloquent (Laravel) 结果到数组

mysql - Laravel 验证器转义数据库名称

php - 拉维尔 : Select from two tables where column in table two =value using eloquent

Javascript原型(prototype)问题

javascript - Firefox 扩展的 'load event' 之前的事件?

javascript - dimple.js 中的缩放示例?

php - 如何使用 codeigniter 通过 CONCAT() 函数更新数据库列值?

php - Notice : Undefined Index. 如何定义索引?