2015-06-12 35 views
0

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

主页(缩小的空间) - 对象:单击按钮,出现表单,提交表单,从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 PAGE:(减少空间)。

<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

您已经创建了一个封闭范围功能getHistory(DOM的准备处理程序中),所以它不会是封闭范围之外访问。如果你想让它外部访问,你需要声明它由两种调用方法共享AA范围(在这种情况下,全球范围内)

移动的方法来全球范围内

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

我们可以使用父引用父框架,然后像下面我们可以执行该功能。 在这种情况下,它可以是:

parent.getHistory() 

但使用的功能像上面我们需要提醒的功能定义出来的文件准备好了,给它更多的范围。然后通过上述方式我们可以访问。

+0

将函数移动到全局范围 - “parent”。不需要。但是,谢谢。 – jpmyob

相关问题