父节点上的jquery调用函数

时间:2015-06-12 03:48:34

标签: javascript jquery ajax

我在html页面上使用jQuery,使用.ajax()将另一个页面加载到div中。 第二页有一个表格。当该表单提交时,我想调用一个函数(位于初始页面上)。目前我得到这个“ReferenceError:getHistory未定义”(其中'getHistory是函数的名称)。

MAIN PAGE(空间缩小) - 对象:点击按钮,表单出现,提交表单,历史记录从ajax调用更新。

<!DOCTYPE html>
<html lang="en" >
<head>...</head>
<body>

    <div id="msg"></div>

    <input type="button" id="AddEvent" value="add" />

    <div id="addForm"></div>

    <div id="history"></div>

    <!-- script references -->
    <script src="js/jquery.min.js" ></script>
    <script src="js/bootstrap.min.js" ></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>

    <script>
        $( document ).ready( function() {
            // Show form
            $( '#AddEvent' ).click( function() {
                $( '#addForm' ).hide();
                $( '#addForm' ).load( 'addform.html', function( response, status, xhr ) {
                    $( '#addForm' ).slideDown( 1000 ).fadeIn( 3000 );
                    if ( status == 'error' ) {
                        var msg = 'Sorry but there was an error loading the form: ';
                        $( '#msg' ).html( msg + xhr.status + ' ' + xhr.statusText );
                    } 
                });
            });

            // function to populate history
            function getHistory() {
                ...AJAX to populate history div...
            }

            // initial load on page load
            getHistory();
        }
    </script>
</body>

表格页面:(缩小空间)。

<form role="form" id="eventform" action="/eventHandeler" method="post" >
    ...
</form>
<script>
$( document ).ready( function() {

    $( '#eventform' ).ajaxForm( function() {

        alert("Thank you for add!");

        // ****** THIS IS WHERE I WANT TO RELOAD THE HISTORY...function on parent page
        getHistory();

    });

});

2 个答案:

答案 0 :(得分:2)

您已在闭包范围内(在dom ready处理程序内)创建了函数getHistory,因此在该闭包范围之外无法访问它。如果要在外部访问它,则需要在两个调用方法共享的范围内声明它(在本例中为全局范围)

将方法移至全局范围

$(document).ready(function () {
    // Show form
    $('#AddEvent').click(function () {
        $('#addForm').hide();
        $('#addForm').load('addform.html', function (response, status, xhr) {
            $('#addForm').slideDown(1000).fadeIn(3000);
            if (status == 'error') {
                var msg = 'Sorry but there was an error loading the form: ';
                $('#msg').html(msg + xhr.status + ' ' + xhr.statusText);
            }
        });
    });


    // initial load on page load
    getHistory();
})

//move it to global scope from the closure scope
// function to populate history
function getHistory() {
    //...AJAX to populate history div...
}

答案 1 :(得分:1)

我们可以使用parent来引用父框架,然后像下面一样我们可以执行该函数。 在这种情况下,它可以是:

parent.getHistory()

但是要使用上面这个函数,我们需要将函数的定义从文档中提取出来,以便为它提供更多的范围。然后通过上面的方式我们可以访问。