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

时间:2014-05-26 17:40:06

标签: php jquery ajax asynchronous synchronous

我有下一个问题:

我有下一个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中获取返回参数的示例,谢谢!

1 个答案:

答案 0 :(得分:1)

您可以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页面(通知/警告/等)返回/回显其他内容,否则您将在客户端获得JSON错误。