twitter-bootstrap 无需刷新的模态表单提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25001610/
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
Modal Form Submission without refresh
提问by Borko Kovacev
I have a modal window that pops up when I want to add a new project to my dashboard. I have gotten it to work with jquery post however, I cannot prevent it from refreshing. What I want to do is after the project is added to the database, show a success message and close the modal window after few seconds and not refresh the page (parent page of modal).
我有一个模态窗口,当我想向仪表板添加新项目时会弹出该窗口。我已经让它与 jquery post 一起工作,但是,我无法阻止它刷新。我想要做的是将项目添加到数据库后,显示成功消息并在几秒钟后关闭模态窗口而不刷新页面(模态的父页面)。
Here is my modal
这是我的 modal
<div class="modal fade" id="add-project-dialog" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Add a new Project</h4>
</div>
<div class="modal-body">
<h3>New Project:</h3>
<form class="form-horizontal" id="add-project-form" action="/projects/add" method="POST">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Project Name</label>
<div class="col-md-4">
<input id="name" name="name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="description">Project Description</label>
<div class="col-md-4">
<input id="description" name="description" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="project_state">Project State</label>
<div class="col-md-4">
<input id="project_state" name="project_state" type="text" placeholder="" class="form-control input-md">
</div>
</div>
</fieldset>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add-btn" class="btn" type="submit">Add</button>
</div>
</form>
</div>
</div>
Here is my project-dashboard.js
这是我的 project-dashboard.js
AddProject = function(){
$(document).ready(function() {
$("#submit").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
}
My views.py
我的 views.py
class AddProject(webapp2.RedirectHandler):
def get(self):
template_values = {
#'greetings': greetings,
#'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), '../templates/project-add.html')
self.response.write(template.render(path, template_values))
def post(self):
project = Project()
project.name = self.request.get('name')
project.description = self.request.get('description')
project.project_state = self.request.get('project_state')
time.sleep(2)
project.put()
self.redirect('/projects')
I have tried removing the self.redirect('/projects')however that only takes me to a blank page that is /projects/add(that is the action in the form).
我已经尝试删除self.redirect('/projects')但是只带我到一个空白页面/projects/add(即表单中的操作)。
采纳答案by Ionic? Biz?u
The issue is that you added .ready(foo)handler inside of the AddProjectfunction. I suppose that document is loaded when AddProjectis called.
问题是您在.ready(foo)函数内部添加了处理程序AddProject。我想那个文件是在AddProject被调用时加载的。
Another issue is that in your HTML, the form has id add-project-form, so you should do $("#add-project-form")instead of $("#submit").
另一个问题是,在您的 HTML 中,表单具有 id add-project-form,因此您应该$("#add-project-form")使用$("#submit").
$(document).ready(function () {
$("#add-project-form").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
});
Take readyhandler outside of the AddProjectfunction and it should work (the submithandler is added).
在ready函数之外使用处理程序AddProject,它应该可以工作(submit添加了处理程序)。
回答by Jaime Gómez
Edit:After some debugging, the answer was to use the right idand proper placing of the javascript code, as noted by the comments.
编辑:经过一些调试后,答案是使用正确id且正确的 javascript 代码放置,如评论所述。
For starters, a refresh is easy to avoid, just make sure to prevent the default event from running; since you're using jQuery, I would recommend doing return falseto end the function, since it both 'prevents default' and 'stops propagation'.
对于初学者来说,刷新很容易避免,只需确保阻止默认事件运行即可;由于您使用的是 jQuery,我建议return false您结束该函数,因为它既 'prevents default' 又 'stops spread'。
So the first thing you should do is check if your javascript code is actually running and not erring in the middle of execution. If everything is fine there, the worst case is that the project is not actually added (server side error) but the page should notrefresh.
因此,您应该做的第一件事是检查您的 javascript 代码是否确实在运行,并且在执行过程中没有出错。如果一切正常存在,最坏的情况是,该项目实际上并没有增加(服务器端错误),但页面应该不会刷新。
Your server side code has nothing to do with the refresh (if it's being properly hiHymaned), so the response doesn't really matter, I would actually return the idof the new project (so you could provide a link for the newly created item or something like that), but i digress...
您的服务器端代码与刷新无关(如果它被正确劫持),因此响应并不重要,我实际上会返回id新项目的(因此您可以为新创建的项目提供链接或类似的东西),但我离题了......
回答by yardpenalty.com
Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh
这是一个片段,不仅可以在不刷新页面的情况下关闭模态,而且在按下 Enter 时它会提交模态并在不刷新的情况下关闭
I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:
我在我的网站上设置了它,在那里我可以有多个模态,一些模态在提交时处理数据,有些则没有。我所做的是为每个进行处理的模态创建一个唯一的 ID。例如在我的网页中:
HTML (modal footer):
HTML(模态页脚):
<div class="modal-footer form-footer"><br>
<span class="caption">
<button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart <i class="fa fa-shopping-cart"></i></button>
<button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel <i class="fa fa-close"></i></a>
</span>
</div>
jQUERY:
查询:
$(document).ready(function(){
// Allow enter key to trigger preloadorders form
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
if($(".trigger").is(".ok")) //custom validation dont copy
$("#PreLoadOrders").trigger("click");
else
return;
}
});
});
As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready()in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close":
正如您所看到的,此提交执行处理,这就是为什么我为此模态使用此 jQuery 的原因。现在假设我在这个网页中有另一个模态,但没有执行任何处理,并且由于一个模态一次打开,我将另一个模态放在$(document).ready()所有页面都获得的全局 php/js 脚本中,我给模态的关闭按钮一个名为的类".modal-close"::
HTML:
HTML:
<div class="modal-footer caption">
<button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
jQuery (include global.inc):
jQuery(包括 global.inc):
$(document).ready(function(){
// Allow enter key to trigger a particular class button
$(document).keypress(function(e) {
if(e.which == 13) {
if($(".modal").is(":visible")){
$(".modal:visible").find(".modal-close").trigger('click');
}
}
});
});
Now you should get no page refreshes on any of your modals if u follow these steps.
现在,如果您按照以下步骤操作,您的任何模态都不会刷新页面。

