【问题标题】:Showing alert after reloading page重新加载页面后显示警报
【发布时间】:2016-11-27 05:13:30
【问题描述】:

我是初学者,刚学写代码,我在提交表单后尝试做一些通知,然后重新加载页面,会显示 alert-success bootstrap,这是代码

// Bootstrap alert
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message){
  $('#alert_placeholder').html('<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>').show(500).delay(3000).hide(500);
}

(function checkIfMsgSent() {
  if (typeof localStorage !== 'undefined') {
    var isMsgSent = JSON.parse(localStorage.getItem("messageSent")); // JSON.parse because we want a boolean

    if (isMsgSent) {
      alert('Message has been sent.');
      // bootstrap_alert.warning('Message has been sent.');
    }

    localStorage.removeItem('messageSent');
  } else {
    // localStorage not defined
    alert('Your browser in incompatible for some features in this website');
  }
});

$('#sentcontact').on('click', function(){
  if (typeof localStorage !== 'undefined') {
    localStorage.setItem('messageSent', 'true');
  } else {
    // localStorage not defined
    alert('Your browser in incompatible for some features in this website');
  }

  window.location.reload();
});

更新解决方案 2 使用的 Javascript

<div class="container">
  <div id="alert_placeholder"></div>
</div>

<section class="contact_us">
  <div class="container">
    <form action="vanilla-form-contact.php" method="post">
      <div class="row">
        <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
          <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
            <div class="control-group">
              <label for="name" class="label-control">Name:</label>
              <input type="text" class="form-control" name="name" id="name" placeholder="Your name..." required>
            </div>
          </div>

          <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
            <div class="control-group">
              <label for="email" class="label-control">Email:</label>
              <input type="email" class="form-control" name="email" id="email" placeholder="Your email..." required>
            </div>
          </div>

          <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="control-group">
              <label for="subject" class="label-control">Subject:</label>
              <input type="text" class="form-control" name="subject" id="subject" placeholder="Your subject..." required>
            </div>
          </div>

          <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="control-group">
              <label for="message" class="label-control">Message:</label>
              <textarea name="message" id="message" cols="30" rows="10" placeholder="Messages..." class="form-control" required></textarea>
            </div>
          </div>
        </div>
        <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <img class="img-responsive" src="img/icon/contact.png" alt="Contact Icon">
            <div>
              <p class="title_contact">Contact:</p>
              <p class="contact_phone"><i class="fa fa-phone-square"></i> +000</p>
              <p class="contact_email"><i class="fa fa-envelope"></i> email@email.com</p>
            </div>
          </div>
          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <img class="img-responsive" src="img/icon/support.png" alt="Contact Icon">
            <div>
              <p class="title_contact">Support:</p>
              <p class="contact_phone"><i class="fa fa-envelope"></i> email@email.com</p>
              <p class="contact_email"></p>
            </div>
          </div>
        </div>
      </div>
      <button type="submit" class="btn-custom" data-dismiss="alert" id="sentcontact">Send It</button>
     </form>

这是我的 html

An error always show up when page reloaded in contact

每次我重新加载页面时它总是显示在我的页面中,而不是在单击提交按钮之后

但是,当我运行该代码时,它只是先显示 bootstrap_alert 然后重新加载页面。我怎样才能让它先重新加载页面然后显示 bootstrap_alert?

【问题讨论】:

  • 我可以看到 2 种可能性。您需要在 localstorage/cookie 中存储状态,或者通过 URL(查询字符串)传递参数,然后在页面加载时检查它。
  • 你能告诉我如何编码吗?

标签: javascript jquery twitter-bootstrap


【解决方案1】:

有很多方法可以做到这一点。实现此目的的一种简单方法是通过 URL 中的参数并在页面加载时检查它。

// Check the URL parameter on page load
$(function(){
    if(getUrlParameter('success') == '1') {
       bootstrap_alert.warning('Message has been sent.');
    }
});

// Set up the click event
$('#sentcontact').on('click', function(){
  if (true){
    var nextUrl = window.location.href;
    nextUrl += (nextUrl.indexOf('?') === -1 ? '?' : '&') + 'success=1'
    window.location = nextUrl;
  }
});

// Simple function to read parameters out of the URL
function getUrlParameter(name) {
    var 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, " "));
}

【讨论】:

  • 我仍然无法在页面重新加载后显示我的消息
  • 控制台有错误吗?也许bootstrap_alert.warning is undefined
  • 控制台中实际上没有错误,但仍然没有显示
  • 将此添加到您的 javascript 并在此处发布您单击发送按钮后输出到控制台的内容:$(function(){ console.log(window.location.href); })
  • 在我输入该代码之前,它总是在控制台中显示错误 Uncaught Error: Syntax error, unrecognized expression: .navbar-nav li a[href*=#]:not([href=#]) , .site-logo a[href*=#]:not([href=#]) 它从 jquery.min.js:2 调用错误,但是您制作的代码不会在控制台中显示错误日志
【解决方案2】:

解决方案 1

当您以编程方式重新加载时,修改 window 中的 href,检查哈希片段 (onload) 并决定显示警报。

(function checkIfMsgSent() {
  var url = window.location.href;
  if ((/#message_sent/).test(url)) {
    alert('Message has been sent.');
    // bootstrap_alert.warning('Message has been sent.');
  }
})();

$('#sentcontact').on('click', function(){
  if (true){
    window.location = window.location.href + "#message_sent";
    window.location.reload();
  }
});

解决方案 2

使用localStorage,但如果浏览器不支持localStorage(几乎所有现代浏览器都有),这将不起作用。

(function checkIfMsgSent() {
  if (typeof localStorage !== 'undefined') {
    var isMsgSent = JSON.parse(localStorage.getItem("messageSent")); // JSON.parse because we want a boolean

    if (isMsgSent) {
      alert('Message has been sent.');
      // bootstrap_alert.warning('Message has been sent.');
    }

    localStorage.removeItem('messageSent');
  } else {
    // localStorage not defined
    alert('Your browser in incompatible for some features in this website');
  }
})();

$('#sentcontact').on('click', function(){
  if (typeof localStorage !== 'undefined') {
    localStorage.setItem('messageSent', 'true');
  } else {
    // localStorage not defined
    alert('Your browser in incompatible for some features in this website');
  }

  window.location.reload();
});

【讨论】:

  • 解决方案1可行,但我的警报通知总是在页面重新加载时显示,如何在单击表单中的提交按钮时重新加载后显示?
  • 更新 当我在 alert function (){ var url = window.location.href; 中重新加载页面时收到此消息if ((/#message_sent/)) { //alert('消息已发送'); bootstrap_alert.warning('消息已发送。'); } },为什么不只显示“消息已发送”?它包含代码
  • 知道了,只要您的网站网址末尾有#message_sent,就会显示警报。 (这是解决方案 1 的副作用)。我建议您使用解决方案 2,这是一种更好、惯用且可靠的方式来处理您的情况。如果有效,请接受答案。 :)
  • 在您的第二条评论中,我看到一个错字,不是((/#message_sent/)) ,应该是(/#message_sent/).test(url)。但是尝试解决方案 2 .. 这是我能想到的最好的 ;)
  • 嗯,我在重新加载页面×function checkIfMsgSent() { if (typeof localStorage !== 'undefined') { var isMsgSent = JSON.parse(localStorage.getItem("messageSent")); // JSON.parse because we want a boolean if (isMsgSent) { alert('Message has been sent.'); // bootstrap_alert.warning('Message has been sent.'); } localStorage.removeItem('messageSent'); } else { // localStorage not defined alert('Your browser in incompatible for some features in this website'); } } 时收到了这条消息,即使我在没有点击提交的情况下重新加载,它总是显示该通知。我真的被困在这里了......
猜你喜欢
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 2019-03-31
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
相关资源
最近更新 更多