变量不断重置为原始值 [英] Variable keeps getting reset to its original value

查看:94
本文介绍了变量不断重置为原始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

function send() {

    var nop = 6;

    var send_this = {
        nop: nop
    };

    $.ajax({

            type: "GET",
            data: send_this,
            url: "example.com",
            success: function(r) {

                var obj = JSON.parse(r);

                nop = obj.nopval;

                /* some other stuffs*/

            }

        )
    };

}

现在,由于我已经将nop设置为6,它将通过6.但是在返回时,json响应obj.nopval将返回12,我想将其设置为nop.这样,下次发送12并返回18,依此类推....

Now, since I already set the nop to 6 , it will pass 6. But on returning, the json response obj.nopval will return 12 which I want to set to nop. So that next time it sends 12 and return 18 and so on....

这里发生的是,它发送6并返回12,但再次发送6并再次返回12.该变量未更新.

What happening here is , it is sending 6 and returning 12 but sending 6 again and returning 12 again. The variable is not getting updated.

推荐答案

您正在声明并初始化函数内部的nop变量,因此该变量将在每次调用该函数时从6开始. nop需要在函数之外的某个地方存在,以使更改得以保留:

You are declaring and initializing the nop variable inside your function, so it will start off at 6 every time the function is called. nop needs to exist somewhere outside your function in order for the changes to persist:

var nop = 6; // outside the function

function send() {
    var send_this = {
        nop: nop
    };

    $.ajax({
        type: "GET",
        data: send_this,
        url: "example.com",
        success: function(r) {
            var obj = JSON.parse(r);
            nop = obj.nopval;
            /* some other stuff*/
        }
    });
}

这篇关于变量不断重置为原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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