从函数返回值> ajax>数据>每个

时间:2015-11-16 22:16:22

标签: jquery ajax each mediawiki-api

在关闭之前,我认为这不是常规的var传递。

我有这个功能,我有点卡住了。我想从每个ajax结果中返回:

function isInCat(cat, check) {
    var toReturn;
    var toReturnOutside;

    $.ajax({
        type: 'POST',
        url: 'http://www.mediawiki.org/w/api.php',
        dataType: 'json',
        data: {
            format: 'json',
            action: 'query',
            prop: 'categories',
            titles: 'Category:' + cat
        }
    }).done(function (data) {
        console.log( data);

        var toReturnOutside;
        var res = data["query"]["pages"];

        $.each(res, function (i, item) {
            var inCat = "";
            inCats0 = item.categories[0];
            if (inCats0) {
                var inCat = inCats0.title;
                if (inCat == "Category:" + check) {
                    console.log(cat + " = " + check); // works
                    // return cat;
                    toReturnOutside = cat; // doesn't go outside :(
                    return false; // stop loop
                }
            }
        });
        toReturn = toReturnOutside;
    });
    return toReturn; // "MediaWiki components" 
}

电话:

var catToTest = "Edit",
    parentToTest = "MediaWiki components";

var val = isInCat(catToTest, parentToTest); // "MediaWiki components", returns undefined

if ( val == parentToTest) {
    $("body").append(catToTest + ' is in Category ' + parentCatToTest);
}

数据结果:

{
    "batchcomplete": "",
    "query": {
        "pages": {
            "17443": {
                "pageid": 17443,
                "ns": 14,
                "title": "Category:Edit",
                "categories": [
                    {
                        "ns": 14,
                        "title": "Category:MediaWiki components"
                    }
                ]
            }
        }
    }
}

问题可能在var res = data["query"]["pages"];,但我无法访问更深层次:/

非工作jsfiddle:http://jsfiddle.net/zro716Le/(Access-Control-Allow-Origin)。 Tampermonkey中的测试工作:http://jsfiddle.net/zro716Le/1/

0 个答案:

没有答案