我试图在第二个ajax调用中使用jQuery选择器更新foreach中的段落标签。我通过将id标记设置为id="spots_,+item.id
来使其唯一,但是我不知道如何在foreach循环之外访问动态id标记。我一直收到“未定义id”错误。以为全局变量可以工作,但没有成功。
//ajax form the get available times to play
$('#form').submit(function(){
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data : $('#form').serialize(),
success: function(response){
$.each(JSON.parse(response), function(i, item) {
var jdate = $('#date').val();
$('<tr>').html("<td>" + item.time + "</td><td>" + '<form class="insideForm" action="/reservations/getSpots" accept-charset="utf-8" method="">' + '<input type="text" name="jtime" value="' + item.time + '"' + "/>" + '<input type="text" name="jdate" value="' + jdate + '"' + ">" + '<input type="submit" class="btn btn-primary" value="Spots">' + '</form>' + "</td><td>" + "Spots:" + '<p class="spots" id="spots_' + id + '"'+ ">" + '<div id="spots"></div>' + '</p>' + "</td>").appendTo('#availableTimes');
});//end loop
//ajax form the get available spots/seats
$('.insideForm').submit(function(){
var form = $(this).closest('form');
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data : $(this).serialize(),
success: function(response){
$('#spots_'+id).html(response);
}//end success
});
return false;
});
}//end success
});
return false;
});//end ajax time form
最佳答案
在.insideForm对象中,只有一个.spots分类段落。
尝试在表单内使用jQuery选择器:
$('.insideForm').submit(function () {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize(),
success: function (response) {
$('.spots', form).html(response);
}//end success
});
return false;
});