nested ajax and xml parsing
While making a nested Ajax call, how do I pass the index of the first loop to the second loop?
Example:
$(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",
开发者_JAVA百科 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 ..
}
I agree with @alpha123 that you should make $title
local to the parseXml
function by using var $title
instead.
I'm guessing that index3
is a typo and that you want to use index
in the parseInnerXml
function. So you must create a closure that captures the index
value. The createParseInnerXmlCallback
function will do this.
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)
});
}
});
}
精彩评论