我的代码一直给我'start'变量未定义的错误。我在initGame函数中定义它,所以我不知道问题是什么。这是相关的代码。
$( document ).ready(function(){
var ctx = $('#myCanvas')[0].getContext("2d");
var WIDTH = $('#myCanvas')[0].width;
var HEIGHT = $('#myCanvas')[0].height;
//...some variables
var gaps = new Point(5, 5)
var start;
//...more variables
//class Point
function Point(x, y){
this.x = x;
this.y = y;
};
//...functions not using variable 'start'
function initGame(){
$.ajax({
type: "Get",
url: "handler/initGameHandler/",
dataType: 'json',
success: function(response, e) {
//do something here if everything goes well
var width = response["width"]
var height = response["height"]
grid_size = new Point(width, height)
x = gaps.x * grid_size.x
y = gaps.y*grid_size.y
start = new Point((WIDTH - x) / 2,
HEIGHT - y);
indicator_x = start.x + padding + chip_radius
},
error: function(data) {
alert("error")
}
});
}
function startGameLoop() {
return setInterval(draw, 10);
}
function onMouseMove(evt) {
if (evt.pageX > canvasMinX && evt.pageX < canvasMaxX) {
temp = evt.pageX - canvasMinX;
var begin_x = start.x + padding
var last_x = start.x + board_size.x - padding
//code not using start
}
}
function mouseClick(evt){
if (evt.pageX > canvasMinX && evt.pageX < canvasMaxX) {
temp = evt.pageX - canvasMinX;
var begin_x = start.x + padding
var last_x = start.x + board_size.x - padding
if (temp >= begin_x && temp <= last_x) {
for (var i=0; i <= grid_size.x; i++) {
var x = start.x + chip_radius + padding
//code not using 'start'
}
}
}
}
function makeBoard(){
rect(start.x, start.y, board_size.x, board_size.y); //throws error here
var x = start.x + chip_radius + padding;
var y = start.y + chip_radius + padding;
};
function draw(){
//code
makeBoard()
//code
}
initGame()
startGameLoop()
init_mouse()
});
我还应该提一下,在我将数据硬编码并且没有从服务器读取之前,即在我实现initGame()函数之前,代码工作正常。
从服务器收到数据没有任何问题。
答案 0 :(得分:2)
在返回ajax请求之前,您的makeboard()
函数正在运行。您的start
变量在您的ajax请求的回调中分配,这可能会在makeboard()
之后运行,因此您会收到未定义的错误。
尝试在回调中运行startGameLoop()
,而不是在initGame()
之后直接运行它。
E.g。下面的内容在您的控制台中就是这样的。
“1”
“3”
“4”
“2”
console.log('1'); // I run first
$.ajax({
url: "/getMyData",
success: function () {
console.log('2'); // I run last
}
});
console.log('3'); // I run 2nd
console.log('4'); // I run 3rd
答案 1 :(得分:1)
&#34;我在initGame函数中定义它&#34;
不,你不是。您在initGame()
函数中的异步Ajax函数的成功处理程序中定义它。只有在initGame()
完成后才会调用成功处理程序,而调用initGame()
的代码完成后
尝试将对startGameLoop()
的调用移动到Ajax成功处理程序中,以便循环不会启动,直到初始化真正完成,即在收到Ajax响应之后。 (您不会显示init_mouse()
的实现,但您可能还需要将调用移至该功能。)
答案 2 :(得分:0)
尝试在AJAX函数中使用回调:
function initGame(callback){
$.ajax({
type: "Get",
url: "handler/initGameHandler/",
dataType: 'json',
success: function(response, e) {
// your code
start = new Point((WIDTH - x) / 2, HEIGHT - y);
indicator_x = start.x + padding + chip_radius
callback();
}...
initGame(function () {
startGameLoop();
init_mouse();
});