我有下一个问题:
我有下一个AJAX:
$.ajax({
data: parametros,
url: 'attack.php',
type: 'get',
beforeSend: function() {
$("#attack").html("Wait please...");
},
success: function(response) {
//Response saying succes attack
$("#attack").html(response);
score = //returned score via AJAX;
}
});
PHP:
//Some BD connections and querys
if ($win == true) {
//The message
echo "You won the battle!";
//The value that must be returned
$score = $score + 10;
}else {
//The message
echo "You been defeted in battle!";
//The value that must be returned
$score = $score + -10;
}
我需要从我的attack.php中获取一些返回值,将其放入我的var分数中。 但我找不到方法,我看到一些帖子说除了异步之外它同步但我不明白...
希望任何人都可以发布一个如何从我的PHP中获取返回参数的示例,谢谢!
答案 0 :(得分:1)
您可以json_encode
来自服务器的响应,然后从中访问多个变量。
$data = array();
if ($win == true) {
//The message
$data['msg'] = "You won the battle!";
//The value that must be returned
$data['score'] = $score + 10;
}else {
//The message
$data['msg'] = "You been defeted in battle!";
//The value that must be returned
$data['score'] = $score -10;
}
echo json_encode($data);
$.ajax({
data: parametros,
url: 'attack.php',
type: 'get',
dataType: 'json', // telling the function to expect json response
beforeSend: function() {
$("#attack").html("Wait please...");
},
success: function(response) {
// accessing array variables via keys
$("#attack").html(response.msg);
score = response.score;
}
});
注意:除了$data
数组之外,确保从php页面(通知/警告/等)返回/回显其他内容,否则您将在客户端获得JSON错误。