[英]Submit multiple forms by their ID using AJAX
我希望使用 AJAX 通過他們的 ID 提交多個表單,ID 是使用下面的 jQuery 找到和生成的。 每個表單當然都有單獨的唯一 ID,當前由變量 i 創建。
<script>
$(document).on('click', '#button', function() {
var wrap = $(this).closest('div.form_wrap');
wrap.find('form').each(function() {
var id = $(this).prop('id');
var i = $('#'+id);
console.log(i);
});
});
</script>
HTML
<?php $f = 0;?>
@foreach ($workouts as $workout)
<?php $formid="form_".$x."_".$f;?>
{!! Form::open(array('route' => 'workoutshared.store', 'method' => 'POST', 'ID' => $formid)) !!}
{{ csrf_field() }}
{{ Form::hidden('user_id', Auth::user()->id)}}
{{ Form::hidden('date', $entry)}}
{{ Form::hidden('weight', $workout->weight)}}
{{ Form::hidden('exercise', $workout->exercise)}}
{{ Form::hidden('reps', $workout->reps)}}
{{ Form::hidden('sets', $workout->sets)}}
{{ Form::checkbox('share', 1, array('class' => 'form-control'))}}
{!! Form::close() !!}
<tr>
<th>{{$workout->exercise}}</th>
<td>{{$workout->weight}}</td>
<td>{{$workout->reps}}</td>
<td>{{$workout->sets}}</td>
</tr>
<?php $f++; endforeach;?>
更新
<script>
$(document).on('click', '#button', function() {
var wrap = $(this).closest('div.form_wrap');
wrap.find('form').each(function() {
var id = $(this).prop('id');
var i = $('#'+id);
console.log(i);
$(i).submit(function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
});
});
</script>
您可以使用以下方法提交所有表格:
wrap.find('form').each(function() {
var id = $(this).attr('id');
var i = $('#'+id);
$(i).submit(function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
});
顯然,使用 this 會獲取表單中已經使用的數據,並使用當前方法將其提交給當前操作。
因此,如果您使用 GET 和 POST 以及不同的提交位置(操作),這基本上是有效的。
編輯:我還根據 jquery 文檔將 .prop() 更改為 .attr(): http: //api.jquery.com/attr/ .prop() 在這種情況下不是正確用法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.