通过 Laravel 中的 js onclick 事件提交数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24234529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:39:29  来源:igfitidea点击:

submit data by js onclick event in Laravel

javascriptphplaravellaravel-4

提问by amir

how to submit a form by js onclick event? I'm using Laravel 4.1.

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

I tried this code

我试过这个代码

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

but I can't get what I want. at the controller I have the following code:

但我得不到我想要的。在控制器我有以下代码:

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

by the way, in chrome console I got the following error:

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

Uncaught TypeError: Cannot read property 'submit' of null

未捕获的类型错误:无法读取 null 的属性“提交”

Can anybody help me with this?

有人可以帮我解决这个问题吗?

回答by Keith Mifsud

As far as I know you should not have more than one tag in a view. I suggest you use ajax to trigger the submit event. However, you don't even have one form open tag but just a a checkbox.

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

I might need some more information but from what I understand you need to submit data to the controller when the checkboxes are clicked.

我可能需要更多信息,但据我所知,当单击复选框时,您需要将数据提交给控制器。

I would do it this way:

我会这样做:

// 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);