jQuery的Ajax回调出的功能范围 [英] jquery ajax callback out of the function scope

查看:101
本文介绍了jQuery的Ajax回调出的功能范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function checkauth(){
       jQuery.getJSON("/users/checkauthjson", null, function(xhr){
           if(xhr.success){ return true;}else{ return false;}
            });
   }

显然,这是不行的,但它说明了什么我想要实现。我想checkauth要返回的检查针对AJAX服务器脚本中的数值。

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.

我如何做到这一点?

推荐答案

的getJSON()默认情况下异步方法,所以你不能依靠它而不做一些调整。 使用阿贾克斯()函数,异步参数设置为false,然后分配结果一个变种,其范围是在checkAuth()函数。

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.

事情是这样的:

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

这篇关于jQuery的Ajax回调出的功能范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆