Jquery Ajax/getJSON Javascript 问题

发布于 2024-12-02 12:33:26 字数 2850 浏览 1 评论 0原文

我仍在试图弄清楚这一切,但我遇到了一个非常奇怪的错误。

我使用的是 getJSON,但在搜索此问题的解决方案后,我发现最好尝试使用 AJAX 函数(用于错误捕获 -> 不会触发)。

在 firebug 中使用断点,如果我慢慢地运行代码,它(大部分)工作得很好(只需要更改一些坐标以获得更好的绘图)。但如果我让它以正常速度运行,它会尝试在返回 json 对象之前执行回调。 firebug 控制台说一切正常(代码 200),但是当检查船舶对象/函数内的 jobj 时,它似乎是“未定义或空”

在断点之后,ajax 调用似乎将“错误”而不是“成功” ”。但它没有触发警报...

另外,响应时间大约为 300-500 毫秒...这正常吗?或者我需要找到更好的服务器吗?

编辑后的代码:

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 正在发送:

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

实时演示:

http://www.schennshome.net/medicalmmj/practice/index.html (代码远非完美,我运行它以尝试在制作动画之前捕获各种错误,但无法克服这一点。)

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).

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). But if I let it run at normal speed, it attempts to do the callback before the json object is returned. 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"

Following the breakpoints, the ajax calls seem to be going to "error" and not "success". But it isn't firing the alert...

Also, the response takes like 300-500ms.... is that normal? 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:

{"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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梅倚清风 2024-12-09 12:33:26

我已经仔细研究了您的源代码,问题实际上并未在您的问题中显示出来。问题出在 Ajax 调用之后的这一行:

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

game.pship 引用 ajax 调用返回的数据,但由于这是异步的,因此将首先评估上面的行,这意味着 < code>game.pship 将不会被定义。

要解决此问题,您需要将当前位于 ajax 调用下方的 init 函数中的所有代码直接包含在 success 回调中。这将阻止在 ajax 调用返回之前评估代码。

它使用断点的原因是它会中断评估,从而允许 ajax 调用在引用 game.pship 之前完成。

编辑

我现在在第 489 行收到错误,指出 player_ship 未定义。这又是由于异步代码的求值顺序造成的。问题在于,player_ship 现在是在 init 的 ajax 函数内定义的,但在该回调之外的 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();
}

然后修改 init 以接受在 success 回调底部调用的回调方法。这样,如果游戏尚未初始化(且 player_ship 尚未定义),它将在 ajax 调用之后执行。

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:

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.

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. This will prevent the code from being evaluated until the ajax call has returned.

The reason that it works with breakpoints is that this interrupts evaluation, which allows the ajax call to complete before game.pship is referenced.

Edit

I'm now getting an error on line 489, stating that player_ship is undefined. 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.

This is how I would rewrite 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. This way, if the game has not been initialized (and player_ship is not yet defined), it will be executed after the ajax call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文