jQuery的:$就成功回调不会让我分配到外部私有变量 [英] jQuery: $.ajax success callback doesn't let me assign to outside private variable

查看:114
本文介绍了jQuery的:$就成功回调不会让我分配到外部私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var doCheck = function() {
    var data;

    $.ajax({
        url: 'check.php',
        data: 'ch=check',
        success: function(resp) {
            data = resp;
        }
    });
console.log(data);
    return data == 1;
};

以上code,不管数据永远只能返回 0 1 。内的成功的回调的范围,这是事实。参数 RESP 0 1 取决于值在输入

The above code, regardless of the data only ever returns a 0 or a 1. Within the scope of the success callback, this is true. The argument resp has a value of 0 or 1 depending on input.

不过,每当我尝试访问私有变量(应该不会受到影响范围),没有任何反应;当的console.log(数据); 被称为所有写入控制台未定义

However, whenever I try to access a private variable (should not be affected by scope), nothing happens; and when console.log(data); is called all that is written to the console is undefined.

这功能没有父母,所以不用担心其他某种范围的干扰。

This function has no parent, so don't worry about some other kind of scope interference.

推荐答案

阿贾克斯是异步的。这就是为什么你要组织你的逻辑和回调:

Ajax is asynchronous. Which is why you have to organize your logic with callbacks:

var doCheck = function(callback) {
    var data;

    $.ajax({
        url: 'check.php',
        data: 'ch=check',
        success: function(resp) {
            callback(data == 1);
        }
    });
};

doCheck(function(result) {
    // result is true or false
});

这篇关于jQuery的:$就成功回调不会让我分配到外部私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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