当用户想要在基本时间表网格中输入类次
时,我有以下函数可以调出模式/对话框
。我使用ajax来发布表单,效果很好,并且按照我的意愿返回。
问题是,当我第二次使用该函数时,无论我第二次输入什么,它都会使用我第一次在 textboxes
中输入的值。
即 尝试1
- 在 11:00:00 - 17:00:00 框中输入
- 传递到 php 页面的值 11:00:00 - 17:00:00
尝试2
- 在 14:00:00 - 22:00:00 框中输入
- 传递到 php 页面的值 11:00:00 - 17:00:00
我设法使用 $("#starttime").val('');
获得清除值的函数。但即使我这样做,在任何后续尝试中,我也无法输入新值。无论我输入什么,它都只会发布空的内容。它也正确传递了所有其他变量,例如date``week
和year
。
function newshiftClick(eid, date, week, year) {
$("#delete-confirm").html("Please input start and finish times for the new shift.<br>\n\
Start: <input type='text' size='8' id='starttime' placeholder='00:00:00'><br>\n\
Finish: <input type='text' size='8' id='finishtime' placeholder='00:00:00'><br>");
$("#delete-confirm").dialog({
resizable: false,
modal: true,
title: "New Shift",
height: 200,
width: 300,
buttons: {
"Yes": function () {
var starttime = document.getElementById("starttime").value;
var finishtime = document.getElementById("finishtime").value;
console.log(starttime);
console.log(finishtime);
console.log(date);
$.ajax({
type: "POST",
url: "ajaxrequest.php",
data: { action: "newshift",
eid: eid,
date: date,
starttime: starttime,
finishtime: finishtime,
week: week,
year: year
},
success: function(response) {
clearSchedule();
document.getElementById("editorpanel").innerHTML = response;
console.log(response);
$("#starttime").val('');
$("#finishtime").val('');
}
});
$(this).dialog('close');
},
"No": function () {
$(this).dialog('close');
}
}
});
}
编辑
这现在是我的 ajax 调用。我按照第一个答案改了一下,确实有道理。然而,它实际上并没有像它应该的那样改变行为。
$.ajax({
type: "POST",
url: "ajaxrequest.php",
data: { action: "newshift",
eid: eid,
date: date,
starttime: $("#starttime").val(),
finishtime: $("#finishtime").val(),
week: week,
year: year
},
success: function(response) {
clearSchedule();
document.getElementById("editorpanel").innerHTML = response;
console.log(response);
$("#starttime").val('');
$("#finishtime").val('');
}
});
我也尝试过在成功函数
的末尾使用$("#delete-confirm").html('');
。
最佳答案
您的问题是这样的:
var starttime = document.getElementById("starttime").value;
var finishtime = document.getElementById("finishtime").value;
当 jQuery 为您构建对话框时评估“Yes”函数时,这些变量将被评估一次。然后它们成为 ajax 调用的闭包/范围的一部分,这就是一个包装。那时它们就变得有点不可变了。
为了解决这个问题,我将删除"is"按钮处理函数的前 5 行,并更改 ajax 调用,使其读取方式如下:
$.ajax({
type: "POST",
url: "ajaxrequest.php",
data: { action: "newshift",
eid: eid,
date: date,
starttime: $("#starttime").val(),
finishtime: $("#finishtime").val(),
week: week,
year: year
},
success: function(response) {
clearSchedule();
document.getElementById("editorpanel").innerHTML = response;
console.log(response);
$("#starttime").val('');
$("#finishtime").val('');
}
});
换句话说,在您发送请求的确切时间获取输入的值;不要将其预加载到您无法控制(或不知道如何)作用域/闭包的变量中。
关于javascript - Jquery ajax - 无法在文本框中设置新值 - 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34801747/