twitter-bootstrap 如何将 PHP 表单放入模态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33236660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 23:16:43  来源:igfitidea点击:

How to put a PHP form into a modal

phphtmltwitter-bootstraptwitter-bootstrap-3bootstrap-modal

提问by user3587175

I have this HTML code for a form in a modal (using Bootstrap)

我有一个模态表单的 HTML 代码(使用 Bootstrap)

<div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="edit-user-modal-label" aria-hidden="true">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">


          <form name="login_form" action="test.php" method="post" role="form">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">Login</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">                  
                      <label for="email">Email:</label>
                      <input type="email" class="form-control" id="email" placeholder="Enter email">                  
                </div>

                <div class="form-group">
                      <label for="pwd">Password:</label>
                      <input type="password" class="form-control" id="pwd" placeholder="Enter password">
                </div>
            </div>

            <div class="modal-footer">
                <input id="submit" name="submit" type="submit" value="Ok" class="btn btn-primary">
            </div>

          </form>

      </div>

    </div>
</div>

The problem is that when I click on the "ok" button, nothing happens. This is the "test.php" file (which I only used to see if it worked)

问题是当我点击“确定”按钮时,什么也没有发生。这是“test.php”文件(我只是用来查看它是否有效)

<html>
    logged
</html>

I'm new in bootstrap so I'm not quite sure about why it does not work as a usual HTML+CSS page. Thanks for your help!

我是引导程序的新手,所以我不太确定为什么它不像通常的 HTML+CSS 页面那样工作。谢谢你的帮助!

EDIT

编辑

I found this AJAX code, tried to adapt it into my code but still didn't work.

我找到了这个 AJAX 代码,试图将它改编成我的代码,但仍然没有奏效。

$(document).ready(function () {
            $("input#submit").click(function(){
                $.ajax({
                    type: "POST",
                    url: "test.php", // 
                    data: $('form.login_form').serialize(),
                    success: function(msg){
                        $("#form-content").modal('hide');   
                    },
                    error: function(){
                        alert("failure");
                    }
                });
            });
        });

By now, I just want to go to another PHP page after pressing the button (I haven't coded the login validation yet).

现在,我只想在按下按钮后转到另一个 PHP 页面(我还没有对登录验证进行编码)。

回答by Ethic Or Logics

I see what is happening, just add this

我明白发生了什么,只需添加这个

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js"></script>
<script>
    $(document).ready(function(){

    $('#submit').click(function(){

      $('#loginModal').modal('show'); 
    });

</script>

回答by Elias Van Ootegem

The most obvious part of your problem is that, while you're performing an AJAX call, you'r not actually preventing the form from submitting. You don't want to submit the page, but instead wait for the ajax request to end, and process the response in your success callback. Since you're using jQuery, the easiest way to do that is to return falsefrom the event callback:

您的问题最明显的部分是,当您执行 AJAX 调用时,您实际上并没有阻止表单提交。您不想提交页面,而是等待 ajax 请求结束,并在成功回调中处理响应。由于您使用的是 jQuery,因此最简单的方法是false从事件回调中返回:

$(document).ready(function () {
            $("input#submit").click(function(){
                $.ajax({
                    type: "POST",
                    url: "test.php", // 
                    data: $('form.login_form').serialize(),
                    success: function(msg){
                        $("#form-content").modal('hide');   
                    },
                    error: function(){
                        alert("failure");
                    }
                });
                return false;//stop form submission
            });
        });

jQuery's return falseis the equivalent of vanilla-JS's:

jQueryreturn false相当于 vanilla-JS:

eventObj.preventDefault();//do not handle event in a normal fashion
eventObj.stopPropagation();//do not propagate event to other handlers

Having said that, your selector and event binding could be better, I'd set an ID for the form (<form id='modalformid'>), and bind the submitevent (which can be triggered by the user pressing enter), and then bind the handler like so:

话虽如此,您的选择器和事件绑定可能会更好,我会为表单 ( <form id='modalformid'>)设置一个 ID ,并绑定提交事件(可以由用户按下 触发enter),然后像这样绑定处理程序:

$('#modalformid').on('submit', function()
{
    var frm = $(this);//reference to the form that is submitted
    $.ajax({
        type: "POST",
        url: "test.php",
        data: frm.serialize(),//serialize correct form
        success: function(msg) {
            //the response from the server is in msg here!
            $("#form-content").modal('hide');   
        },
        error: function(){
            alert("failure");
        }
    });//your ajax call here
    return false;
});

I'd also check the console to make sure you're including all JS dependencies (ie jQuery) beforeyou're calling $(document).ready()and double-check for name conflicts (in console console.log($)and console.log($ === jQuery)).
Lastly, the $('form.login_form')selector is not reliable: ID's are by definition unique. Classes aren't. using $('form.login_form')could, in theory, match more than one form. rule of thumb: classes are useful for CSS rules, not so much for JS event handling (delegation asside), if you want to handle a single form/element: use an ID.

我还会检查控制台以确保在调用之前包含所有 JS 依赖项(即 jQuery)$(document).ready()并仔细检查名称冲突(在控制台console.log($)和 中console.log($ === jQuery))。
最后,$('form.login_form')选择器不可靠:根据定义,ID 是唯一的。类不是。using$('form.login_form')理论上可以匹配不止一种形式。经验法则:如果你想处理单个表单/元素,类对 CSS 规则很有用,而不是对 JS 事件处理(委托除外)有用:使用 ID。

回答by EternalHour

I agree with Elias. In the situation of an AJAX call you don't want to submit the form because page will reload and you'll never get a response.

我同意埃利亚斯的观点。在 AJAX 调用的情况下,您不想提交表单,因为页面将重新加载并且您永远不会得到响应。

In your JS, you're binding a click event, which is good, but your inputis type="submit"which will cause an issue.

在你的 JS 中,你绑定了一个 click 事件,这很好,但你的inputistype="submit"这会导致问题。

First thing, remove that.

第一件事,删除它。

<input id="submit" name="submit" value="Ok" class="btn btn-primary">

Secondly, in JQuery you're referencing an invalid selector for the form.

其次,在 JQuery 中,您引用了表单的无效选择器。

$('form.login_form').serialize()

There is no login_formclass. Since AJAX handles the request for you I would suggest using an id instead and minimizing the attributes.

没有login_form课。由于 AJAX 为您处理请求,我建议使用 id 代替并最小化属性。

<form id="login_form" role="form">

Based on the HTML you provided I have to assume you were wanting to hide #loginModalinstead of #form-content.

根据您提供的 HTML,我必须假设您想要隐藏#loginModal而不是#form-content.

$(document).ready(function () {
    $("input#submit").click(function(){
        $.ajax({
            type: "POST",
            url: "test.php",
            data: $('form#login_form').serialize(),
            success: function(msg){
                $("#loginModal").modal('hide');
                // show validation error if applicable   
            },
            error: function(){
                alert("failure");
            }
        });
    });
});