嵌套的ajax和xml解析

时间:2011-09-05 22:02:41

标签: xml ajax parsing nested

在进行嵌套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 ..
}

1 个答案:

答案 0 :(得分:0)

我同意@ alpha123,您应该使用$title代替parseXml功能var $title。{/ p>

我猜测index3是一个拼写错误,您想在index函数中使用parseInnerXml。因此,您必须创建一个捕获index值的closurecreateParseInnerXmlCallback函数将执行此操作。

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)
            });
        }
    });
}