我有一个函数,我希望在结果完成时返回一个数组。我想在退出函数之前返回JSON数据。如何使函数等待JSON数据在退出函数之前返回?
function callback(results) {
console.log("callback");
return results;
}
function UserNameMatchResults(userName) {
if (userName == '') return;
var results = [];
$.getJSON('json_data.php', { method: 'matchUsers', userName: userName }, function(data) {
$.each(data, function(key, value) {
console.log("Name Match >>> " + value.user_id);
results.push(value.user_id);
});
callback(results);
});
}
我还尝试了response.when
和response.done
,函数UserNameMatchResults
不会等待JSON数据返回。
function callback(results) {
console.log("callback");
return results;
}
function CertMatchResults(certName) {
if (certName == '') return;
var results = [];
var response = $.getJSON('json_data.php', { method: 'matchCerts', certName: certName }, function(data) {
$.each(data, function(key, value) {
console.log("Cert Match >>> " + value.user_id);
results.push(value.user_id);
});
});
response.done(function(results) {
callback(results);
});
}
答案 0 :(得分:2)
您没有正确关闭括号!
function UserNameMatchResults(userName) {
if (userName == '') return;
var results = [];
$.getJSON('json_data.php', { method: 'matchUsers', userName: userName }, function(data) {
$.each(data, function(key, value) {
console.log("Name Match >>> " + value.user_id);
results.push(value.user_id);
)}//HERE
callback(results);
});
}