简体   繁体   English

jQuery Ajax / getJSON Javascript问题

[英]Jquery Ajax/getJSON Javascript Question

I am still trying to figure all this out and I am coming across a really weird error. 我仍在尝试找出所有这些,并且遇到了一个非常奇怪的错误。

I was using getJSON but after searching for solutions to this problem, I found that it was better to try to use the AJAX function (for error capturing -> which isnt firing). 我使用的是getJSON,但是在寻找解决此问题的方法之后,我发现最好尝试使用AJAX函数(用于错误捕获->这不是触发)。

Using breakpoints in firebug, if I go slowly through the running code, it works (mostly) fine (just need to change some coordinates for better drawing). 在Firebug中使用断点,如果我缓慢地浏览正在运行的代码,它(通常)可以正常工作(只需要更改一些坐标即可更好地绘制)。 But if I let it run at normal speed, it attempts to do the callback before the json object is returned. 但是,如果我让它以正常速度运行,它将尝试在返回json对象之前进行回调。 The firebug console says everything works ok (code 200), but when examining the jobj inside ship object/function it appears to be "undefined or null" Firebug控制台说一切正常(代码200),但是在检查舰船对象/功能内部的jobj时,它似乎是“未定义或为空”

Following the breakpoints, the ajax calls seem to be going to "error" and not "success". 在断点之后,ajax调用似乎将变为“错误”而不是“成功”。 But it isn't firing the alert... 但这并没有发出警报...

Also, the response takes like 300-500ms.... is that normal? 另外,响应时间大约为300-500ms。...这正常吗? or do I need to find a better server? 还是需要寻找更好的服务器?

Edited Code: 编辑代码:

var init = (function(){
            thisplayer = new player();
            jQuery.ajax({type: "GET", url: "shipdata.php", processData: true, data: {shipid:1}, dataType: "json",
                success: function(json) {
                    var pship = new ship(json);
                    player_ship = $.extend(thisplayer, pship);
                    starfield = new starfield();
                    for(var i = 0; i < player_ship.enemytotal; i++) {
                            $.ajax({
                                type: "GET",
                                url: "shipdata.php",
                                processData: true,
                                data: {shipid:Math.round((Math.random()*2+2))},
                                dataType: "json",
                                success: function(json) {
                                    var enemy = new ship(json);
                                    game.enemies.push(enemy);
                                },
                                error: function(x,y,z) {
                                // x.responseText should have what's wrong
                                    alert(x.responseTest);
                                }
                            });
                        }
                    game.initialized = true;
                },
                error: function(x,y,z) {
                // x.responseText should have what's wrong
                    alert(x.responseTest);
                }
            });


        })

.............................. ....................................

var ship = (function(json){
        var self = this;
        jobj = jQuery.parseJSON(json.responseText);
        self.height = jobj.height;
        self.width = jobj.width;
        self.xinit = jobj.xinit;
        self.yinit = jobj.yinit;
        self.speed = jobj.speed;
        self.weapons = jobj.weapons;
        self.maxlasers = jobj.maxlasers;
        self.imagesrc = jobj.imgurl;
        self.lasers = [];
        self.x = self.xinit;
        self.y = self.yinit;

JSON being sent in: JSON正在发送:

{"height":75,"width":50,"xinit":275,"yinit":525,"speed":3,"weapons":[1,2],"maxlasers":2,"imgurl":"images\/ship.png"}

Live Demo: 现场演示:

http://www.schennshome.net/medicalmmj/practice/index.html (The code is far from being perfect, Im running through it to try and catch the various errors before animating, but cant get past this.) http://www.schennshome.net/medicalmmj/practice/index.html (代码远非完美,我正在运行它以尝试在制作动画之前捕获各种错误,但无法通过。)

I've dug through your source code, and the problem is not actually shown in your question. 我已经仔细阅读了您的源代码,但问题并未真正显示出该问题。 The problem is with this line, which follows your Ajax call: 问题出在这行,跟在您的Ajax调用之后:

player_ship = $.extend(thisplayer, game.pship);

game.pship refers to the data returned by the ajax call, but since this is asynchronous, the above line will be evaluated first, which means game.pship will not be defined. game.pship指的是ajax调用返回的数据,但是由于这是异步的,因此将首先评估以上行,这意味着将不会定义game.pship

To fix this, you need to include all of the code in your init function that is currently below the ajax call directly in the success callback. 要解决此问题,您需要将所有代码包含在您的init函数中,该函数当前直接位于success回调中的ajax调用下方。 This will prevent the code from being evaluated until the ajax call has returned. 这将阻止代码在ajax调用返回之前被评估。

The reason that it works with breakpoints is that this interrupts evaluation, which allows the ajax call to complete before game.pship is referenced. 它与断点一起工作的原因是这会中断评估,从而允许ajax调用在引用game.pship之前完成。

Edit 编辑

I'm now getting an error on line 489, stating that player_ship is undefined. 我现在在第489行收到一条错误消息,指出player_ship是未定义的。 This is again because of the evaluation order of async code. 再次是由于异步代码的评估顺序。 The problem is that player_ship is being defined inside the ajax function in init now, but is being referenced in gameLoop , outside of this callback. 问题在于, player_ship现在在init的ajax函数中定义,但在该回调之外的gameLoop被引用。

This is how I would rewrite gameLoop : 这就是我重写gameLoop

var callback = function() {
  game.canvas.clearCanvas();
  drawStarfield();

  if(player_ship.alive && game.initialized && !(game.loading)) {
    drawPlayer();
    drawLaser();
    drawEnemies();
  }
};

if(game.initialized==false) {
  init(callback);
} else {
  callback();
}

And then amend init to accept a callback method which is called at the bottom of your success callback. 然后修改init以接受在success回调的底部调用的回调方法。 This way, if the game has not been initialized (and player_ship is not yet defined), it will be executed after the ajax call. 这样,如果游戏尚未初始化(并且尚未定义player_ship ),它将在ajax调用后执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM