我仍在努力掌握 jQuery、AJAX 和 JSON。
在我的应用程序中,我有以下下拉选择菜单:
<select id="serviceload" name="serviceload"></select>
我用另一个我认为没有必要在此处显示的函数自动填充选项。只要知道上面的 SELECT 有 1 个或多个 OPTION 值即可。
接下来是内容部分:
<div class="row" id="completeProfile">
// series of DIVS and TABLES
</div>
最初,内容部分是隐藏的,因此用户只能看到下拉菜单:
$('#completeProfile').hide();
现在,jQuery:当用户从下拉菜单中选择一个选项时,我将使用下一段代码。每次他们选择一个新选项时,查询都会重新运行,并且新内容会显示在屏幕上,除非他们选择空白选项。
$('#serviceload').change(function () {
var page = $('#serviceload').val();
if (page == "") {
$('#completeProfile').hide();
} else {
$.post('api/profileSearch.php', {
page: page
}, function (data) {
var obj = JSON.parse(data);
$('#portBody').empty();
var htmlToInsert = obj.map(function (item) {
return '<tr><td>' + item.PORT + '</td><td>' + item.NAME + '</tr>';
});
$('#portBody').html(htmlToInsert);
});
// I do several more $.post to return data into specific tables
// Take note of this next $.post
$.post('api/vesselSearch.php', {
page: page
}, function (data) {
var obj = JSON.parse(data);
$('#vesselinfo').empty();
var htmlToInsert = obj.map(function (item) {
return '<tr><td><a href="#" class="editVesselLink" data-toggle="modal" data-vessel="' + item.VESSEL_NAME + '">Edit</a></td><td>' + item.VESSEL_NAME + '</td></tr>';
});
});
// after all the queries are ran, and the data is returned, now we show the content
$('#completeProfile').show();
}
});
在上面的容器信息部分中,有一个部分打印一个可以单击的超链接,它会打开一个模式窗口。这是出于编辑目的。此功能正常。
这就是问题所在。
回到内容部分,还有另一个超链接,可打开模式窗口以添加新容器。
<h3>Vessels</h3> / <a href="#" id="vesselInfoLink" data-toggle="modal">Add New</a>
这将打开“添加新船只”模式。在该模式中,有一个带有按钮的表单,其内容如下:
<button type="button" id="addVesselSubmit">Add</button>
单击此按钮时,会将用户输入的值发送到更新表的 PHP 脚本。
$('#addVesselSubmit').click(function () {
var addservice = $('#addservice').val();
var addvessel = $('#addvessel').val();
$.post('api/addInfo.php', {
addservice: addservice,
addvessel: addvessel
}, function (data) {
// here is where my problem lies
if (data == 0) {
alert("Vessel was not saved");
} else {
alert("Vessel was saved");
// At this point, I need to rerun the main function above so that it shows the vessel that was added immediately to the content section without a page refresh
}
});
});
因此,在上面的代码中,如果新记录成功保存到表中,则整个内容部分应重新运行,而无需刷新页面,新记录会自动显示在 VesselInfo 部分中。
我认为用于显示内容的代码需要变成一个主函数,可以在 addVesselSubmit 成功时调用,但我不知道如何继续。
重申我的问题:我需要能够保存新记录,并将新记录打印到页面而无需刷新页面。
最佳答案
$.post('api/addInfo.php', {
addservice: addservice,
addvessel: addvessel
}, function (data) {
// here is where my problem lies
if (data == 0) {
alert("Vessel was not saved");
} else {
alert("Vessel was saved");
// At this point, I need to rerun the main function above so that it shows the vessel that was added immediately to the content section without a page refresh
//Trigger a change on element
$('#serviceload').trigger('change');
/*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
}
});
关于javascript - jQuery AJAX 中的另一个函数完成后重新运行原始函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32103031/