0

我有对象“游戏”,当我调用创建游戏时,它使用 jquery ajax ......一切正常,但是当我想从 ajax 成功函数 addLoadEvent 调用它时它没有调用它,当我尝试从 createGame 调用这个函数时(评论这里的一部分代码)它的作品......你知道为什么我不能从ajax成功中调用它吗?我从成功尝试控制台日志,它在控制台中打印,所以 ajax 运行良好。谢谢大家的帮助

        var game=new ttt_game();
        function addLoadEvent(func) {
            var oldonload = window.onload;
            if (typeof window.onload != 'function') {
                window.onload = func;
            } else {
                window.onload = function() {
                    if (oldonload) {
                        oldonload();
                    }
                    func();
                }
            }
        }            
        function ttt_game () {
            this.createGame = createGame;

            function createGame(){
                /*addLoadEvent(function(){
                            document.getElementById('player1_n').textContent=player1+':';
                            document.getElementById('player2_n').textContent=player2+':';
                            document.getElementById('turn').textContent='Čaká sa na príchod súpera.';
                        });*/
                $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: {'function': 'create','game_id': game_id,'player1': player1},
                    dataType: "json",
                    success: function(data){
                        addLoadEvent(function(){
                            document.getElementById('player1_n').textContent=player1+':';
                            document.getElementById('player2_n').textContent=player2+':';
                            document.getElementById('turn').textContent='Čaká sa na príchod súpera.';
                        });
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                });
            }
        } 
        game.createGame();
4

1 回答 1

0

它看起来像 on addLoadEvent,您正在添加一个window.onload处理程序,当您从调用它时调用它createGame时它window.onload尚未触发但是当您从成功处理程序调用它时,onload 事件可能已经触发,因为 ajax 是异步处理的

于 2013-08-22T11:16:25.727 回答