jQuery - 使用 AJAX 从另一个页面加载帖子表单
我正在尝试使用 JQuery 提交表单而不重新加载页面。虽然这与独立页面上的 jQuery 表单插件配合得很好,但我需要它在我使用 AJAX 加载的页面上工作。
<script type="text/javascript">
$('#LoadForm').click(function() {
$('#formDiv1').load('FormGen.asp');
});
</script>
然而,当我在加载的表单上单击“提交”时,表单会提交并刷新页面,而不是仅使用 AJAX 提交。
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
如果我将代码放在我调用的页面中并使用该独立版本,它就会完美运行。但是,当我尝试从另一个页面加载表单时,它不起作用。
I am trying to use JQuery to submit a form without reloading the page. Although this works well with the jQuery Form Plugin on a standalone page I need it to work on a page I've loaded with AJAX.
<script type="text/javascript">
$('#LoadForm').click(function() {
$('#formDiv1').load('FormGen.asp');
});
</script>
When I click submit on the loaded form however, the form submits and refreshes the page instead of submitting with just AJAX.
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
If I put the code in the page I call and use that standalone it works perfect. It doesn't however work when I am attempting to load the form from another page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您的页面加载时,页面中的元素
#myForm
尚不存在(因为您使用 ajax 加载),因此ajaxForm()
插件未初始化。当你的 ajax 内容成功加载时,你应该初始化它。为此,请使用加载完成时执行的 .load() 方法的回调参数发生:
When your page load, the element
#myForm
does not exist yet in the page (because you load with ajax) so theajaxForm()
plugin is not initialized.You should initialize it when your ajax content has successfully loaded. To do so, use the callback parameter of the .load() method that is executed when the loading has occurred:
更新:
eerrrr...我的错,没有正确阅读问题 - Didier Ghys 的答案似乎更合适。
click()
将事件处理程序绑定到“click”JavaScript 事件。执行脚本时绑定完成。由于您通过ajax加载了游览表单,我想在加载表单之前调用了click()函数,因此没有绑定。
尝试使用
live()
函数:UPDATE:
eerrrr... my bad, didn't correctly read the quesion - Didier Ghys's answer seems more appropriate.
click()
binds an event handler to the "click" JavaScript event. The binding is done when the script is executed.Since you laod tour form by ajax, I suppose the
click()
function is called before the form is loaded, and thus there is no binding.Try using the
live()
function :您需要使用
on()
方法绑定到 AJAX 加载的内容 - http ://api.jquery.com/on/You need to use the
on()
method to bind to things being loaded by AJAX - http://api.jquery.com/on/