jQuery.post() scope issue while trying to overwrit

2019-08-14 13:25发布

This question already has an answer here:

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条回答
爷的心禁止访问
2楼-- · 2019-08-14 13:48

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);
查看更多
登录 后发表回答