javascript - 重新加载页面后如何隐藏模式并显示另一个模式?
问题描述
我有一个模态形式。提交表单时,我希望关闭模式,重新加载页面,然后显示成功模式。
但是当我单击提交时发生的事情是成功模式显示在模式表单上,然后页面重新加载而没有模式。
这是我的代码:
$.ajax({
type: "POST",
url: "includes/handlers/ajax_submit_profile_post3.php",
data: $('form.profile_post3').serialize(),
success: function(msg) {
$("#post_form3").modal('hide');
location.reload();
$("#successModal").modal('show');
},
error: function() {
alert('Failure');
}
});
解决方案
location.reload
已经刷新了你的页面,所以你的成功回调中的最后一行不再执行(或者至少它对重新加载的页面没有影响)。所以重新加载后不会显示模态
您可以做些什么来归档您的目标是使用特殊参数刷新页面并在页面加载时检查该参数(然后显示模式)
所以不要location.reload()
做类似(已编辑)的事情:
window.location.search = updateQueryStringParameter(window.location.search,"success","true")
在页面本身(加载时)上执行类似(已编辑)的操作:
$(document).ready(function() {
if(getParameterByName("success",window.location.href) == "true"){
$("#successModal").modal('show');
}
});
所以重新加载的页面现在将包含一个额外的 url 参数,页面本身会检查它并在参数存在时打开成功模式
编辑:代码现在适用于所有 url(如果已经有 url 参数),因此您还需要添加两个 javascript-helper 函数:
//https://stackoverflow.com/a/6021027/1578780
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
//https://stackoverflow.com/a/901144/1578780
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
推荐阅读
- .htaccess - htaccess 无法重写为正确的 URL
- oracle - 使用 jdbc 执行 Spark
- tcp - 找出 RTP 最大大小
- r - dateRangeInput、selectInput 和反应函数 R 闪亮
- amazon-cloudformation - 如何在 CloudFormation 中使用一个条目创建多个资源(只是名称不同)
- javascript - 如何在 typeorm 中指定 ormcofig.js
- rabbitmq - RabbitMQ 动态创建监听器
- angular - mat-tab 内的 mat-table 中的重复行
- postgresql - 如何加入每个组的填充值?
- javascript - 我怎样才能间隔地按顺序翻转卡片?