Javascript refuses to return anything
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'));
开发者_JAVA技巧 $('.description').html(owner.descripion);
})
The above code is supposed to read a JSON file, compare some query strings to test for validity and then return the object if the request is valid. Problem is, no matter what I do, getGood
refuses to return any value to my owner
variable. I've tried having it return the different values around it. I was just trying to get it to return anything I could. It needs to return cval
. The alert at the bottom, however, always says "undefined/null".
EDIT
Because apparently people think I am just that retarded:
YES, it gets to the return statement. Yes, qHash == qs('hash'), I'm not asking you to check every if/loop/etc. I already know all of that works. I'm asking, why does my return statement not end up setting owner
to what it is supposed to.
The callback passed to "$.getJSON()" is executed asynchronously. It is therefore just not possible to return a value from it.
Instead, pass in the code that needs to act on the value as a function parameter. The callback function can then pass the value into that function as a parameter.
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);
});
JavaScript isn't "refusing to return" anything. You're just not asking it to.
You're doing
var owner=getGood(qs('cat'),qs('subp'));
but getGood
does not return
any value. The only return
statement is in the function (key, val)
inside getGood
which returns from that function, not from getGood
.
精彩评论