0

回调始终为空

// calling the function
var returnArray = getArrayData(fileName, function(data) {
    return data;
})
alert(returnArray); // output says undefined

function getArrayData(fileName, callback) {
    var arrayData = [];
    $.getJSON("sendRequestFile", {
        fileContent: fileName
    }, function(data) {
        $.each(data, function(index, value) {
            if (value === "false") {} else if (value === "") {} else {
                arrayData[index] = value;
            }
        });
        alert(arrayData); // see data without no problems
    });
    alert(arrayData); // empty
    callback(arrayData); // undefined
}​
4

1 回答 1

3

Ajax is asynchronous, run the callback within the complete callback.

$.getJSON("sendRequestFile", {
    fileContent: fileName
}, function(data) {
    $.each(data, function(index, value) {
        if (value === "false") {} else if (value === "") {} else {
            arrayData[index] = value;
        }
    });
    callback(arrayData); // worky
});
//alert(arrayData); // empty
//callback(arrayData); // undefined​
于 2012-11-19T22:24:46.427 回答