在进行嵌套Ajax调用时,如何将第一个循环的索引传递给第二个循环?
示例:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "url1",
dataType: "xml",
async: false,
success: parseXml
});
});
function parseXml (xml){
$title = $(xml).find("title");
//find every Tutorial and print the author
$title.each(function(index)
{
//alert($(this).text());
if (index != 0) {
$("#container").append('<div id=' + index + '></div>');
$('#' + index).text($(this).text());
$.ajax({
type: "GET",
url: $(xml).find('content').eq(index).attr('src'),
dataType: "xml",
async: false,
success: parseInnerXml(index3)
});
}
});
}
function innerXml(xml2, index3)
{
// is this how i get the value of index3
// also will xml2 contain the new xml doc ..
}
答案 0 :(得分:0)
我同意@ alpha123,您应该使用$title
代替parseXml
功能var $title
。{/ p>
我猜测index3
是一个拼写错误,您想在index
函数中使用parseInnerXml
。因此,您必须创建一个捕获index
值的closure。 createParseInnerXmlCallback
函数将执行此操作。
function parseXml (xml){
function createParseInnerXmlCallback(index) {
return function () {
parseInnerXml(index);
}
}
var $title = $(xml).find("title");
//find every Tutorial and print the author
$title.each(function(index)
{
//alert($(this).text());
if (index != 0) {
$("#container").append('<div id=' + index + '></div>');
$('#' + index).text($(this).text());
$.ajax({
type: "GET",
url: $(xml).find('content').eq(index).attr('src'),
dataType: "xml",
async: false,
success: createParseInnerXmlCallback(index)
});
}
});
}