jQuery - Loading form submission in DIV of parent

2019-08-08 19:01发布

问题:

I have the following code, which works perfectly ... so far. But I want to next have a form load ... read below this code for an explanation.

Main Page:

<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>

Now, in content1.php , all links (a=href... ) work great and load into the #right_section div.

But on content1.php, I also have some forms, and I would like them to also load into the same div #right_section. A sample of a form is as follows:

sample form in content1.php:

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

How can I get a form (any form, might be multiple on the page) to load into the div #right_section, without loading over the entire page (which it does now)

Thanks !

回答1:

You'll need to replace the form's submit handler, similarly to the way you replaced the normal click handler on links.

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