JavaScript 单击“提交”按钮后如何显示成功消息?

我有以下的javascript代码,以提交一个新的联系我们的表格。在按下提交按钮后,我希望html将显示一条成功消息。

知道我该怎么做吗?

$(function() {
  $('#contact-form').validator()

  $('#contact-form').on('submit', function(e) {
    // if the validator does not prevent form submit
    if (!e.isDefaultPrevented()) {
      const url = 'http://localhost/api/contact/'

      // POST values in the background the the script URL
      $.ajax({
        type: 'POST',
        url: url,
        data: $(this).serialize(),
        success: function(data) {
          // data = JSON object that contact.php returns

          // we recieve the type of the message: success x danger and apply it to the
          const messageAlert = 'alert-' + data.type
          const messageText = data.message

          // let's compose Bootstrap alert box HTML
          const alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>'

          // If we have messageAlert and messageText
          if (messageAlert && messageText) {
            // inject the alert to .messages div in our form
            $('#contact-form').find('.messages').html(alertBox)
            // empty the form
            $('#contact-form')[0].reset()
          }
        }
      })

      return false
    }
  })
})

You should append your alertBox variable to an existing element in your HTML. For example, if your HTML element is has a div id of message:

$("#message").append(alertBox);

More info about append can be found here: http://api.jquery.com/append/

Simply add the alertBox html to your page.

// let's compose Bootstrap alert box HTML
const alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>'

$(“html”).append(alertBox)

If you want the alert to appear somewhere specific you target a different element on your page.

You can add this code in script tag

<script> $("#contact-form").submit(_=> alert("You have successfully submitted"));</script>