jQuery.post() scope issue while trying to overwrite global variable [duplicate]

余生颓废 提交于 2020-01-25 06:32:10

问题


I'm facing some difficulties in my code related to scope. Here is my code:

<script type="text/javascript">
    var totalHoras = {};
    var dadosCategorias = {"teste": "1234"};
    var t; // timeout handler para exibição de feedback para o usuário

    $().ready(function() {
        // obtém dados das categorias
        var obterDadosCategorias = function() {
            $.post(
                "{{ baseRoute }}/cadastro/categoria/listar"
                , {
                    "ajax": "true"
                }
            ).done(function(data) {
                var obj = $.parseJSON(data);
                if (obj.result) {
                    console.log(dadosCategorias); // returns 'object{"teste": "1234"}'
                    dadosCategorias = obj.data;
                    console.log(dadosCategorias); // returns 'string(11) "it works!!!"'
                } else {
                    alert('Erro interno: não foi possível obter os dados das categorias');
                }
            });
        };

        obterDadosCategorias();
        console.log(dadosCategorias); // returns 'object{"teste": "1234"}'

The question is: why the hell is the third call of console.log returning the orginal var value? isn't is suposed to be overwriten?

The console was suposed to be

'object{"teste": "1234"}'
'string(11) "it works!!!"'
'string(11) "it works!!!"'

But it is

'object{"teste": "1234"}'
'string(11) "it works!!!"'
'object{"teste": "1234"}'

I've trie to use the "context" option with window in $.ajax() function, but does not work too :(


回答1:


Thanks to the comments guys! :D

I've found the answer. The problem wasn't the scope at all. Actually, the calls to console.log() wasn't in the order of the script. The calling order was 312 before, now it is 123 :D I changed the ajax method to $.ajax() instead of $.post() and set the option 'async' to false to achieve this, like so:

<script type="text/javascript">
    var totalHoras = {};
    var dadosCategorias = {"teste": "1234"};
    var t; // timeout handler para exibição de feedback para o usuário

    $().ready(function() {
        // obtém dados das categorias
        var obterDadosCategorias = function() {
            $.ajax(
                "{{ baseRoute }}/cadastro/categoria/listar"
                , {
                    "type": "POST"
                    , "async": false
                    , "data": {
                        "ajax": "true"
                    }
                }
            ).done(function(data) {
                var obj = $.parseJSON(data);
                if (obj.result) {
                    console.log(1, dadosCategorias);
                    dadosCategorias = obj.data;
                    console.log(2, dadosCategorias);
                } else {
                    alert('Erro interno: não foi possível obter os dados das categorias');
                }
            });
        };

        obterDadosCategorias();
        console.log(3, dadosCategorias);


来源:https://stackoverflow.com/questions/26090272/jquery-post-scope-issue-while-trying-to-overwrite-global-variable

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