如何让Twitter Bootstrap模式在表单提交时保持打开状态?

我试图弄清楚是否有一种相对简单的方法(我对JQuery不熟练)在表单提交后保持模态打开。 (表格包含在模态中)。

如果表单成功或有错误,我的PHP将显示它们,但是一旦按下提交按钮,模态就会关闭。

如果我重新加载表单,我可以看到相应的成功或错误消息,所以一切正常,但我希望最终用户看到该消息,然后单击以关闭该模式。

如果有帮助,我可以发布我的代码。

谢谢。

<?php $success_message = "

Thank you, your message has been sent.

"; $success = false; // we assume it and set to true if mail sent $error = false; // set and sanitize our form field values $form = array( 'Name' => $sanitizer->text($input->post->name), 'Email' => $sanitizer->email($input->post->email), 'Phone number' => $sanitizer->text($input->post->phone), 'Type of client' => $sanitizer->text($input->post->client_type), 'Service client is after' => $sanitizer->text($input->post->service), 'Further information' => $sanitizer->textarea($input->post->information) ); $required_fields = array( 'name' => $input->post->name, 'email' => $input->post->email ); // check if the form was submitted if($input->post->submit) { // determine if any fields were ommitted or didn't validate foreach($required_fields as $key => $value) { if( trim($value) == '' ) { $error_message = "

Please check that you have completed all the required fields.

"; $error = true; } } // if no errors, email the form results if(!$error) { $message = ""; $to_name = "My name"; $to = "me@me.com"; $subject = "Contact Form request"; $from_name = "My Website"; $from = "do-not-reply@my-site.com"; $headers = "From: $from_name "; foreach($form as $key => $value) $message .= "$key: $value\n"; require_once("./scripts/PHPMailer/class.phpmailer.php"); $mail = new PHPMailer(); $mail->CharSet = "UTF8"; $mail->FromName = $from_name; $mail->From = $from; $mail->AddAddress($to, $to_name); $mail->Subject = $subject; $mail->Body = $message; if ($mail->Send()) { $success = true; } } } ?>

提交表单时,即使表单的action是同一页面,也会重新加载页面(空操作也表示同一页面)。

我想你想再次加载页面后重新打开模态。 猜测你使用的是method="post"表单,你的代码应该是这样的:

          

为了不关闭模态窗口,即不刷新整个页面,需要通过ajax调用将表单值提交到php脚本。

为简单起见,我将在这里使用jQuery

 $(function() { $('#your_form_id').on('submit', function(event) { event.preventDefault(); $.ajax({ url: "your_php_script.php", type: "POST", data: {"formFieldName" : formFieldValue}, // here build JSON object with your form data dataType: "json", contentType: "application/json" }).done(function(msg) { // this is returned value from your PHP script //your PHP script needs to send back JSON headers + JSON object, not new HTML document! // update your "message" element in the modal $("#message_element_id").text(msg); }); }); }; 

您还可以使用window.stop()来阻止模型关闭和整个刷新,就像点击浏览器中的停止按钮一样。