【问题标题】:Bootstrap Contact Form not posting引导联系表未发布
【发布时间】:2018-01-19 03:43:13
【问题描述】:

我正在按照本教程创建表单:

https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form

在联系表单 HTML 的底部,我添加了脚本:

  <script src='https://code.jquery.com/jquery-1.12.0.min.js'></script>
  <script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'>   </script>
  <script src='js/validator.js'></script>
  <script src='js/contact.js'></script>

验证器文件来自我下载的 Bootstrap。我知道它有效,因为它会在我填写表格时验证我的表格。

当我提交表单时,没有任何反应。我在控制台中收到以下错误:

  POST http://www.example.com/php/contact.php 404 (Not Found)

我将 php 文件放在一个 php 文件夹中,因此该部分已更改,但其他所有内容都相同。我已经尝试将 php 文件放在与联系页面相同的文件夹中并得到类似的消息:

  POST http://www.example.com/contact.php 404 (Not Found)

我想知道是不是因为我使用的是 node 和 express。我想在下面的 index.js 文件中做些什么?

这是我的 index.js:

  const express = require('express');
  const  app = express();
  const port = process.env.PORT || 3000;

  app.use(express.static('public'));
  app.set('view engine', 'ejs');

  app.get('/', function (request, response) {
      response.render('index');
  });

  app.get('/projects', function (request, response) {
      response.render('projects');
  });

  app.get('/about', function (request, response) {
      response.render('about');
  });

  app.get('/contact', function (request, response) {
      response.render('contact');
  });

  app.listen(port, function () {
       console.log('Listening on port ' + port);
 });

这是联系页面上的表单 - HTML:

<form id="contact-form" method="post" action="php/contact.php" role="form">
  <div class="messages"></div>
  <div class="controls">
      <div class="row">
          <div class="col-md-6">
              <div class="form-group">
                  <label for="form_name">Firstname *</label>
                  <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
                  <div class="help-block with-errors"></div>
              </div>
          </div>
          <div class="col-md-6">
              <div class="form-group">
                  <label for="form_lastname">Lastname *</label>
                  <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
                  <div class="help-block with-errors"></div>
              </div>
          </div>
      </div>
      <div class="row">
          <div class="col-md-6">
              <div class="form-group">
                  <label for="form_email">Email *</label>
                  <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
                  <div class="help-block with-errors"></div>
              </div>
          </div>
          <div class="col-md-6">
              <div class="form-group">
                  <label for="form_phone">Phone</label>
                  <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
                  <div class="help-block with-errors"></div>
              </div>
          </div>
      </div>
      <div class="row">
          <div class="col-md-12">
              <div class="form-group">
                  <label for="form_message">Message *</label>
                  <textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
                  <div class="help-block with-errors"></div>
              </div>
          </div>
          <div class="col-md-12">
              <input type="submit" class="btn btn-success btn-send" value="Send message">
          </div>
      </div>
      <div class="row">
          <div class="col-md-12">
              <p class="text-muted"><strong>*</strong> These fields are required. Contact form template by <a href="http://bootstrapious.com" target="_blank">Bootstrapious</a>.</p>
          </div>
      </div>
  </div>
</form>

contact.php:

<?php
    $from = 'Demo contact form <demo@domain.com>';

    $sendTo = 'Demo contact form <demo@domain.com>';

    $subject = 'New message from contact form';

    $fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); 

    $okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';

    $errorMessage = 'There was an error while submitting the form. Please try again later';

    error_reporting(E_ALL & ~E_NOTICE);

    try
    {
      if(count($_POST) == 0) throw new \Exception('Form is empty');

      $emailText = "You have a new message from your contact form\n=============================\n";

      foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
      }

      $headers = array('Content-Type: text/plain; charset="UTF-8";',
        'From: ' . $from,
        'Reply-To: ' . $from,
        'Return-Path: ' . $from,
      );

      mail($sendTo, $subject, $emailText, implode("\n", $headers));

      $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
    catch (\Exception $e)
    {
      $responseArray = array('type' => 'danger', 'message' =>   $errorMessage);
    }


    // if requested by AJAX request return JSON response
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&      strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      $encoded = json_encode($responseArray);

      header('Content-Type: application/json');

      echo $encoded;
    }
   // else just display the message
   else {
    echo $responseArray['message'];
   }

contact.js:

  $(function () {

  // downloaded validator files from http://1000hz.github.io/bootstrap-validator

    $('#contact-form').validator();

    // when the form is submitted
    $('#contact-form').on('submit', function (e) {

        // if the validator does not prevent form submit
        if (!e.isDefaultPrevented()) {
            var url = "contact.php";

            // 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 receive the type of the message: success x danger and apply it to the 
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    // let's compose Bootstrap alert box HTML
                    var 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;
          }
       })
  });

【问题讨论】:

  • 您的/php/contact.php ...文件未找到,将contact.php放在php文件夹外并尝试action="contact.php"
  • 所以您正在为您的站点运行两台服务器?您如何阻止 express 尝试为 /php/contact.php 提供服务?
  • @hungerstar 是的,我是个菜鸟,正在尝试 Express 但不需要它。我将删除 Express 并重试,但我不确定如何重做我的 index.js。将不得不研究。
  • @saurabh-mistry 我尝试将contact.php放在文件夹之外并使用contact.ejs,但这没有用。我怀疑 HUNGERSTAR 对我的问题是正确的。
  • 如果您是初学者,我会坚持使用单一服务器和后端服务器端语言。表单的帖子必须使用 PHP 而不是 Express 是否有特定原因?

标签: javascript php html twitter-bootstrap express


【解决方案1】:

我对节点和表达不够深入,无法完全了解您的 JavaScript 是否可靠。我能给出的唯一建议是尝试该教程中显示的 JS,并将文件放在同一个位置。基本上都是重新创建。

之后,尝试将contact.php 放入php 文件夹并修复该操作。看看这是否有效。

如果是这样,那么您就会知道这是您的 JS。我知道 Bootstrap 依赖于 JQuery,因此如果您已经将 JQuery 用于 Bootstrap 的其他功能,您可能需要考虑使用他们的脚本。如果没有,那么只需一步一步地发送大量错误消息,直到找到问题所在。

抱歉,我无法提供更好的帮助。祝你好运!

【讨论】:

  • 欢迎来到 SO!一般来说,如果您没有很好的答案,最好对问题发表评论。
  • 知道了。对此感到抱歉。
  • @InternetArtisan 我有脚本标签链接到:
  • 对,但我要说的是,您似乎正在尝试使用 node 和 express 重写教程提供的 JS。我的问题是“为什么?”如果 Bootstrap 已经需要 JQuery 来运行,那为什么不使用教程中给出的 JQuery 脚本呢?您的 Express 脚本是否更优化或者只是个人喜好?我的想法是在站点构建中不要使用太多框架,所以如果客户要求我使用 Bootstrap,那么我会尝试坚持使用 JQuery 来处理其他 JavaScript,通常会放入 noConflict 函数以防止脚本阻碍彼此。
  • @JacobWood,我还发现我无法发表评论,因为我没有 50 个代表。我最终会到达那里,但它解释了为什么我没有看到该选项。
猜你喜欢
  • 2021-07-26
  • 2018-12-03
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 2017-09-13
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多