2015-05-26 76 views
1

我有以下代码,该代码完美无缺......迄今为止。但我想接下来有一个表单加载...阅读以下代码的解释。jQuery - 在父页面(?)的DIV中加载表单提交

主页:

<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,没有加载整个页面(它现在所做的)

谢谢!

+0

一切都应该加载到DIV。我没有看到任何形式为什么不同的理由。 – Barmar

+0

你是说当你提交一个表单时,它的结果应该加载到DIV中,而不是重新加载页面? – Barmar

+0

正确...但现在,它只是覆盖整个浏览器窗口。 – Vacek

回答

2

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

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); 
     } 
    }); 
}); 
+0

谢谢。我假设JS进入主页? ...试过了,并没有工作。 – Vacek

+0

是的,它就像你已经拥有的JS一样。 – Barmar

+0

应该在JS中引用#right_section或data-target?我尝试了很多东西,但并不想工作。 – Vacek

相关问题