doujing5726 2019-04-21 14:43 采纳率: 0%
浏览 2299

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
    }
  })
})
  • 写回答

3条回答 默认 最新

  • duanmu0834 2019-04-21 14:56
    关注

    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/

    评论

报告相同问题?

悬赏问题

  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)