Using $.post within a javascript function, cannot assign value to a variable?

泪湿孤枕 提交于 2019-12-13 18:18:33

问题


I'm trying to use $.post within a function, get the results, then return the function true or false based on the results of the $.post callback. However, the callback seems to occur, AFTER the return event of the parent function.

Here's the current code the ret variable is always undefined but if I alert() it within the $.post callback, it returns the correct result;

function elementExists(key, type, path, appid, pid){
    var ret;
    $.post('?do=elExists', {key: key, type: type, path: path, appid: appid, pid: pid},function(data){
        ret = data;                         
    });

    alert(ret);
    return ret;

}

回答1:


As you've discovered the post is done asynchronously. If you want it to be synchronous, you'll need to use the ajax method and set the async parameter to false. It would be better, however, to acknowledge that the post is asynchronous and build your code so that the action performed by the callback is independent of the method that invokes the post. Obviously, you really want to do something other than the alert, but without knowing what it's hard to advise you how to refactor this.

EDIT: I understand that your code is checking to see if something exists, but it is checking that for a purpose. If we knew what the purpose was, then it might be possible to recommend how to accomplish that in the callback so that the method could be refactored.




回答2:


function elementExists(key, type, path, appid, pid){
        $.post('?do=elExists', {key: key, type: type, path: path, appid: appid, pid: pid},function(data){
           alert(data);
        });
  }

the function(data) is a call back (Asynchronous) you can't return values like that.

it that callback is not called until the page is done being called, but your "return ret" is executing immediately after you call $.post

If you want to set it syncronous set async : false

See the docs http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype




回答3:


The problem is that your code executes asynchronously. That is alert(ret) is actually called before ret = data, which happens when the Ajax request is completed.

You can either make your ajax calls synchronous (not recommended) by using the async option, or redesign your code.



来源:https://stackoverflow.com/questions/824431/using-post-within-a-javascript-function-cannot-assign-value-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!