【问题标题】:How to do form validation using HTML and jQuery without redirecting to another page?如何使用 HTML 和 jQuery 进行表单验证而不重定向到另一个页面?
【发布时间】:2017-10-22 19:54:51
【问题描述】:

我编写了一个 HTML 表单和脚本来验证表单。问题是,每当我提交表单时,我都会被重定向到一个告诉我“找不到您的文件”的页面。

我有什么特定的方式来调用脚本吗?或者我可以通过什么方式强制它运行而不重定向我?

<form id="bioform" action="/action_page.php">
  <label>Biography</label><br>
  <textarea placeholder="Enter bio here" name="bio" rows="10" cols="50"></textarea><br><br>
  <label>Update Biography Picture</label><br><br>
  <input type="file" name="bioimage"><br><br>
  <button type="submit" onclick="function()">Update</button><br>
</form>

<script>
  $(document).ready(function () {
    $('#bioform').validate({
        rules: {
          bio {
            required: true,
            minlength: 5,
          },
        }
        messages: {
          bio {
            required: 'Please enter a biography.',
            minlength: 'Please enter a valid biography.',
          },
        }
        });
  });
</script>

【问题讨论】:

    标签: php jquery html


    【解决方案1】:

    将 enctype="multipart/form-data" 添加到表单标签

        <form id="bioform" action="/action_page.php" enctype="multipart/form-data">
         <label>Biography</label><br>
         <textarea placeholder="Enter bio here" name="bio" rows="10" cols="50">
         </textarea><br><br>
         <label>Update Biography Picture</label><br><br>
         <input type="file" name="bioimage"><br><br>
         <button type="submit" onclick="function()">Update</button><br>
        </form>
    

    【讨论】:

    • 这似乎没什么区别。我是否必须在我的目录中创建一个名为 action_page.php 的文件?我假设它会自动创建。
    • 您没有在您的目录中创建文件 action_page.php ?那么你从哪里得到发布的值??
    • 用户应该在网页上输入值
    • 如果您不想在目录中创建文件,请从标签中删除操作属性,这些值将发布在同一页面上,您也可以将脚本放置在同一页面上...
    【解决方案2】:

    在指定发送到哪里时是否需要正斜杠?例如:

    <form id="bioform" action="/action_page.php">
    

    应替换为:

    <form id="bioform" action="action_page.php">
    

    【讨论】:

    • 删除斜线不会改变它。我仍然被重定向。我是否必须在我的目录中创建一个名为 action_page.php 的文件?我假设它会自动创建。
    • 是的,您必须在同一目录中创建文件,因为它不会自动完成。
    • 另外,PHP 文件应该处理数据,而不是存储数据。
    • 那么我会把我的脚本放到 PHP 文件中吗?
    • 您可以在文件中放置一个 PHP 脚本来处理信息。您可以在tutorialspoint.com/php 获得教程。
    【解决方案3】:

    由于您使用的是 jQuery,请尝试使用:

    e.preventDefault()

    e.preventDefault() 方法停止默认操作 元素从发生。例如:阻止提交按钮 提交表格。阻止链接跟随 URL。

    此外,您需要在 &lt;form&gt; 标签内添加 method 属性,其值为 POST 以及 enctype="multipart/form-data",因为您正在处理文件上传。

    转到这个小提琴并检查它是否适合你:https://jsfiddle.net/z0db4vq0/1/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多