开发者

How to return value from anonymous function in jquery

function test() {
    var flag1 = false;
    if ($('#field1').attr('value') || !$('#field1').attr('value')) {
        $.aja开发者_如何学编程xSetup({
            cache: false
        });
        $.getJSON("test_term.php", {
            'term1': $("#cde").attr('value'),
            'cd3': $("#cde3").attr('value')
        }, function(data) {
            if (data[0].stss == 'K') {
                var status = data[0].stss;
                flag1 = true;

            } else if (data[0].stss == 'U' || data[0].stss == '') {
                flag1 = false;
                return;
            }
        });
    }
    alert("ANonymous value" + flag1);
    return flag1;
}

How do I return the "flag1" value from the anonymous function used in getJson()? It is always returning false which is being referred at the top.


This is not possible the way you try it.

Ajax calls are asynchronous, they return whenever they are ready to. The inner function you've passed to getJSON() runs well after the outer function test() has finished running.

That means - whatever you want to happen when the Ajax call returns - put it into the callback function. Do no work with flags and return values.

E.g.

function do something(flag) {
  // do something
}

function test() {
  if ($('#field1').attr('value') || !$('#field1').attr('value')) {
    $.ajaxSetup({
        cache: false
    });
    $.getJSON("test_term.php", {
        'term1': $("#cde").attr('value'),
        'cd3': $("#cde3").attr('value')
    }, function(data) {
        if (data[0].stss == 'K') {
            var status = data[0].stss;
            doSomething(true);
        } else if (data[0].stss == 'U' || data[0].stss == '') {
            doSomething(false);
        }
    });
  }
}


The problem is not with the anonymous function, but with its asynchronous nature.

That method is a callback to be executed when the AJAX request is completed.

For that reason, your

alert("ANonymous value" + flag1);
return flag1;

will run before the callback and so the flag1 has not yet been altered by that method.

You will need to put whatever you want to happen after the JSON data is retrieved, in the callback method.


The call-back handlers are not going to run until the ajax call comes back, so you can't guarantee that flag1 will be updated. You should have a separate function that gets called to take the processing to the next step.

You may also have an issue with variable scope.. You can put the declaration for flag1 above the function and it will be global.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜