嵌套.ajax()调用的JavaScript / jQuery变量范围问题

我很难将变量postData传递给嵌套的子.ajax()调用,后者是一个序列化的jQuery数组对象。 postData成功传递给第一个.ajax()调用,但是当我尝试在第二个.ajax()调用中使用它时,它不会发布任何表单元素,因为该级别的变量未定义:

 $(".myForm").submit(function () { var postData=$(this).serializeArray(); $.ajax({ type : "POST", async : false, cache : false, url : "./insertComment.php", data : postData, success: function() { $.ajax({ type : "POST", async : false, cache : false, url : "./getComments.php", data : postData, success: function(comments) { $(".Comments").html(comments); } }); } }); return false; }); 

我尝试创建第二个变量_postData尝试将变量保持到下一个.ajax()调用,但它不成功(也尝试了var _postData=$(this).parent().serializeArray();但我仍然没有’能够使变量永久化):

 $(".myForm").submit(function () { var postData=$(this).serializeArray(); $.ajax({ type : "POST", async : false, cache : false, url : "./insertComment.php", data : postData, success: function() { var _postData=$(this).serializeArray(); $.ajax({ type : "POST", async : false, cache : false, url : "./getComments.php", data : _postData, success: function(comments) { $(".Comments").html(comments); } }); } }); return false; }); 

我尝试实现所谓的JavaScript闭包(我仍然没有完全理解),但这导致了更多未定义的变量和更多的失败:

 $(".myForm").submit(function () { var postData = function() { $(this).serializeArray(); }(); $.ajax({ type : "POST", async : false, cache : false, url : "./insertComment.php", data : postData, success: function() { $.ajax({ type : "POST", async : false, cache : false, url : "./getComments.php", data : postData, success: function(comments) { $(".Comments").html(comments); } }); } }); return false; }); 

我尝试搜索并尝试实现其他几种技术,包括jQuery遍历( .parent() .filter()等),但是没有成功。 我知道这对许多人来说是一个常见的问题,但到目前为止我还没有找到一个简单易懂的解决方案。 任何建议将不胜感激。 谢谢!

试试这个:

 $(".myForm").submit(function () { var postData=$(this).serializeArray(); $.ajax({ type : "POST", async : false, cache : false, url : "./insertComment.php", data : postData, success: (function(pData) { // capture the posted data in a closure var _postData = pData; return function() { $.ajax({ type: "POST", async: false, cache: false, url: "./getComments.php", data: _postData, success: function(comments) { $(".Comments").html(comments); } }); } })(postData) // execute the outer function to produce the colsure }); return false; }); 

这是我最终做的事情:

 $(".myForm").submit(function () { var postData = $(this).serializeArray(); // Gets all of the form elements var myID = $(this.ID).val(); // Takes only a single value from the form input named ID $.ajaxSetup({ data : "ID=" + myID // Sets the default data for all subsequent .ajax calls }); $.ajax({ type : "POST", async : false, cache : false, url : "./insertComment.php", data : postData, // Overwrites the default form data for this one instance only, including all form elements success: function() { $.ajax({ type : "POST", async : false, cache : false, url : "./loadComments.php", // Notice there is no data: field here as we are using the default as defined above success: function(comments) { $(".Comments").html(comments); } }); } }); return false; });