为什么getJSON不等待响应?

时间:2015-09-23 19:01:56

标签: jquery json

我有一个函数,我希望在结果完成时返回一个数组。我想在退出函数之前返回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.whenresponse.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);
       });
    }

1 个答案:

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