【问题标题】:jQuery - Loading form submission in DIV of parent page (?)jQuery - 在父页面的 DIV 中加载表单提交(?)
【发布时间】:2015-05-26 00:24:21
【问题描述】:

我有以下代码,它运行良好......到目前为止。但我想接下来有一个表单加载...阅读下面的代码以获得解释。

主页:

<li><a href="content1.php" class="load-external" data-target="#right_section">Some Content</a></li>
<div id="right_section"></div>

<script>
$('body').on('click', 'a.load-external', function(e){
var target = $( $(this).attr('data-target') );
target.load( $(this).attr('href') );
e.preventDefault();
});
</script>

content1.php

<li><a href="content2.php" class="load-external" data-target="#right_section">Some Content 2</a></li>

现在,在 content1.php 中,所有链接 (a=href...) 都可以正常工作并加载到 #right_section div 中。

但在 content1.php 上,我也有一些表单,我希望它们也加载到同一个 div #right_section。表单示例如下:

content1.php 中的示例表单:

<form action="report_output.php" method="get" id="graphIt">

如何让一个表单(任何表单,页面上可能有多个)加载到 div #right_section,而不加载整个页面(现在可以)

谢谢!

【问题讨论】:

  • 所有内容都应该加载到 DIV 中。我看不出表格应该不同的任何原因。
  • 您是说当您提交其中一个表单时,其结果应该加载到 DIV 中,而不是重新加载页面?
  • 正确...但是现在,它只是覆盖了整个浏览器窗口。

标签: javascript php jquery html forms


【解决方案1】:

您需要替换表单的提交处理程序,类似于替换链接上的普通点击处理程序的方式。

HTML:

<form action="report_output.php" class="load-external" method="get" id="graphIt" data-target="#right_section">

JS:

$('body').on('submit', 'form.load-external', function(e) {
    e.preventDefault();
    var target = $($(this).data('target'));
    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        dataType: 'html',
        success: function(response) {
            target.html(response);
        }
    });
});

【讨论】:

  • 谢谢。我假设 JS 在主页上? ... 试过了,还是不行。
  • JS 中是否应该有对 #right_section 或 data-target 的引用?我已经尝试了很多东西,但它不想工作。
  • $(this).data('target') 得到data-target
  • 好的,我搞定了。非常感谢。我在导致问题的 report_output.php 页面(预加载器)中有一个 div ....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多