我正在尝试在另一个Ajax成功函数中进行Ajax调用,但它不知何故不起作用。我在控制台中收到以下错误。我不明白这意味着什么:
Object {readyState:0,getResponseHeader:.ajax / v.getResponseHeader(),getAllResponseHeaders:.ajax / v.getAllResponseHeaders(),setRequestHeader:.ajax / v.setRequestHeader(),overrideMimeType:.ajax / v.overrideMimeType (),statusCode:.ajax / v.statusCode(),abort:.ajax / v.abort(),state:.Deferred / d.state(),always:.Deferred / d.always(),then :. Deferred / d.then(),10 more ...}
我在对象
中找到了类似下面的内容statusText:“SyntaxError:指定了无效或非法字符串”
JS
//Update the board with the moves so far made
var updateBoard = function() {
var style;
$.ajax({
type: "POST",
url: "engine/main.php",
data: {code: 2},
success: function(response) {
if(response != "") {
var obj = JSON.parse(response);
lastClick = obj[obj.length - 1].player;
$(obj).each(function (i, val) {
if (val.player == 1) {
style = "cross";
}
else if (val.player == 2) {
style = "circle";
}
$('td[data-cell="' + val.cell + '"]').html(val.sign).addClass(style);
});
if(obj.length > 2) {
makeDecision();
}
}
else {
lastClick = null;
$('td').html("").removeClass();
}
setTimeout(updateBoard, 1000);
}
});
};
updateBoard();
function makeDecision() {
console.log('starting decision function');
$.ajax({
type: "engine/main.php",
data: {code: 3},
success: function(winner) {
console.log('end');
console.log(winner);
},
error: function(data) {
console.log(data);
}
});
}
PHP
if(isset($_POST['code'])) {
$code = $_POST['code'];
//Handle player number on game start
if($code == 1) {
if (!isset($_COOKIE['gamePlay'])) {
header('Location: index');
}
$playerCode = $_COOKIE['gamePlay'];
$player = $playersHandler->getPlayer($playerCode);
echo $player;
}
// Update board with new moves
else if($code == 2) {
$currentPosition = $gameHandler->getMoves();
echo $currentPosition;
}
else if($code == 3) {
$result = $code; //$gameHandler->decide();
echo $result;
}
//Reset Board
else if($code == 4) {
$gameHandler->reset();
}
}
答案 0 :(得分:3)
您正在type
函数ajax调用中将无效字符串传递给makeDecision
属性。您应该将其设置如下:
type: 'POST',
url: 'engine/main.php',
...
而不是
type: 'engine/main.php'
确保以下行
var obj = JSON.parse(response);
返回数组,而不是对象。如果obj
不是数组,则obj.length
为undefined
答案 1 :(得分:0)
您可以在ajaxComplate事件中再次调用ajax,如下所示:
$( document ).ajaxComplete(function() {
$.ajax({
type: "post",
url: 'engine/main.php',
data: {code: 3},
success: function(winner) {
console.log('end');
console.log(winner);
},
error: function(data) {
console.log(data);
}
});
});
答案 2 :(得分:0)
你无法直接在javascript中获取对象的长度obj.length
如果你得到了正确的响应。获得这样的Parsed对象的长度..
var length = Object.keys(obj).length;
然后
lastClick = obj[length-1].player;
正确使用这样的$.each
..
$.each(obj,function (i, val){
//code
});