开发者

jquery ajax callback out of the function scope

开发者 https://www.devze.com 2022-12-28 00:34 出处:网络
func开发者_高级运维tion checkauth(){ jQuery.getJSON(\"/users/checkauthjson\", null, function(xhr){
func开发者_高级运维tion checkauth(){
       jQuery.getJSON("/users/checkauthjson", null, function(xhr){
           if(xhr.success){ return true;}else{ return false;}
            });
   }

Obviously, that does not work, but it illustrates what i want to achieve. I want checkauth to return a value which is checked against an ajax server script.

How do i do this?


getJson() is an asynchronous method by default, so you cannot rely on it without doing some adjustments. Use .ajax() function, setting async param to false, and then assign result to a var whose scope is in the checkAuth() function.

Something like this:

function ceckAuth() {
  var ret = false;
  $.ajax({
    url: '/users/checkauthjson',
    dataType: 'json',
    data: '',
    async: false,
    success: function(result) { ret = result.success; },
    error: ...
  });
  return ret;
}
0

精彩评论

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