簡體   English   中英

javascript | 單擊“提交”按鈕后如何顯示成功消息

[英]javascript | How to display a success message after clicking the submit button

我有以下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
    }
  })
})

您應該將alertBox變量附加到HTML中的現有元素。 例如,如果您的HTML元素具有div消息:

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

有關append的更多信息,請訪問: http//api.jquery.com/append/

只需將alertBox html添加到您的頁面即可。

// 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)

如果您希望警報顯示在特定位置,則可以在頁面上定位不同的元素。

您可以在腳本標記中添加此代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM