Javascript拒绝返回任何内容

Fre*_*nöw 0 javascript return

getGood = function(v,x) {
    $.getJSON('json/products.json', function(data) {
        $.each(data, function(key, val) {
            if (v.toLowerCase() == key.toLowerCase()) {
                $.each(val.products, function(ckey, cval) {
                    if (x.toLowerCase() == ckey.toLowerCase()) {
                        var dval=new Date().getDay();
                        var qHash=hex_md5(v+x+qs('cst')+dval).toLowerCase();    
                        if (qHash == qs('hash')) {
                            return dval;
                        } else {
                            window.location.replace('/errors/418.html');
                        }
                    }                
                });
            }
        });
    });
}

$(document).ready(function() {
    var owner=getGood(qs('cat'),qs('subp'));
    alert(owner==null);
    $('.content_title').html(qs('subp'));
    $('.description').html(owner.descripion);
})
Run Code Online (Sandbox Code Playgroud)

上面的代码应该读取一个JSON文件,比较一些查询字符串以测试有效性,然后在请求有效时返回该对象.问题是,无论我做什么,都getGood拒绝向我的owner变量返回任何值.我试过让它返回它周围的不同值.我只是想让它尽可能地回报.它需要回归cval.但是,底部的警报总是说"undefined/null".

编辑

因为显然人们认为我只是那种迟钝的:

是的,它到达return语句.是的,qHash == qs('hash'),我不是要求你检查每个if/loop/etc.我已经知道所有这些都有用.我问,为什么我的返回声明最终没有设置owner为它应该是什么.

Poi*_*nty 6

传递给"$ .getJSON()"的回调是异步执行的.因此,无法从中返回值.

相反,将需要对值进行操作的代码作为函数参数传递.然后回调函数可以传递值该函数作为参数.

function getGood(v, x, handleOwner) {
  $.getJSON('json/products.json', function(data) {
      $.each(data, function(key, val) {
          if (v.toLowerCase() == key.toLowerCase()) {
             $.each(val.products, function(ckey, cval) {
                if (x.toLowerCase() == ckey.toLowerCase()) {
                    var dval=new Date().getDay();
                    var qHash=hex_md5(v+x+qs('cst')+dval).toLowerCase();    
                    if (qHash == qs('hash')) {
                        handleOwner(dval); // calling the handler function here
                    } else {
                        window.location.replace('/errors/418.html');
                    }
                }                
            });
        }
     });
  });
}

//
getGood(qs('cat'),qs('subp'), function(owner) {
  alert(owner);
});
Run Code Online (Sandbox Code Playgroud)