通过ajax获取参数?(同步,异步)


Get parameters via ajax? (sync, async)

我有下一个问题:

我有下一个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;
}

我需要从attak.php中获得一些返回值,将其放入我的var分数中。但我找不到路,我看到一些帖子说要同步做,除了异步,但我不明白…

希望任何人都能发布一个如何从我的PHP中获取返回参数的例子,谢谢!

您可以从服务器json_encode您的响应,然后从中访问多个变量。

php

$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);

jQuery

$.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页面(notices/warnings/etc(没有返回/回显其他内容,否则客户端会出现JSON错误。