2014-04-25 2 views
1

저는 게임을 만들고 있습니다. 조각이 움직이면 ('.draggable'), 이동을 확인한 다음 데이터베이스에 저장하는 첫 번째 아약스 호출 (move_script.php로)을 만들어야합니다. 완료되면 두 번째 ajax 호출 (past_moves.php)을 실행하고 데이터베이스를 쿼리하여 새 이동을 작성하려고합니다. 제 문제는 두 번째 아약스 호출이 현재 이동이 있기 전에 결과를 꺼내는 경우가 있다는 것입니다. microtime()을 사용했습니다. 무슨 일이 일어나고 있는지보고 PHP 코드에서, 그리고 가장 최근의 결과가 나오지 않을 때마다 두 번째 아약스 스크립트가 먼저 완료됩니다. (대부분의 경우 가장 최근의 결과가 나옵니다. 그러나 매번 5 ~ 15 회마다 무작위로 나타납니다.) 첫 번째 작업이 완료 될 때까지 두 번째 ajax 호출이 실행되지 않도록하려면 어떻게해야합니까?자바 스크립트를 선형으로 실행 시키십시오.

<script> 
      $(function() { 

       $(".draggable").draggable({ 

        stop: function(event, ui) { 
         var start = $(this).attr('id') 

         //ajax call number 1 
         $.ajax({ 
          type: "POST", 
          url: "../move_script.php", 
          data: { start: start } 
         }).done(function(msg) { 
          //alert("Data Saved: " + msg); 
          $("#chessboard").html(msg); 
         }); 

       //ajax call number 2 
       $.ajax({ 
        type: "POST", 
        url: "../past_moves.php", 
         data: {} 
        }).done(function(moves) { 
        $("#past_moves").html(moves); 
        }); 
        } 
       }); 
     }); 
     </script> 

답변

1

둥지 아약스가

//ajax call number 1 
$.ajax({ 
    type: "POST", 
    url: "../move_script.php", 
    data: { start: start } 
}).done(function(msg) { 
    //alert("Data Saved: " + msg); 
    $("#chessboard").html(msg); 
    //ajax call number 2 
    $.ajax({ 
     type: "POST", 
     url: "../past_moves.php", 
      data: {} 
     }).done(function(moves) { 
      $("#past_moves").html(moves); 
     }); 
    }); 
}); 

이 중첩이 처음이 완료 될 때까지 대기 할 두 번째 전화를 강제로 호출

코드 감사드립니다.

0

첫 번째 ajax 호출의 콜백에 두 번째 ajax 호출을 두어 첫 번째 ajax 호출이 완료된 후에 만 ​​실행되도록하십시오. 그렇지 않으면 ajax가 비동기이기 때문에 요청을 시작한 다음 계속 진행합니다 (이 경우 두 번째 ajax를 시작). 나는 "done"메소드에 익숙하지 않다. 아마도 이미 가지고있는 함수에 넣을 수있을 것이다.

$.ajax({ 
    type: "POST", 
    url: "../move_script.php", 
    data: { start: start }, 
    success: function(data){ 
     //data is whatever the ajax returns. is it msg in this case? 
     //put second ajax call here 
    }, 
    error: function(jqXHR, textStatus, errorThrown){ 
     //might not need here, but this is example of callback which will be executed instead of success if server returns an error 
    }, 
    complete: function(jqXHR, textStatus){ 
     //another useful callback to know about - will execute after success or error 
    } 
}) 

https://api.jquery.com/jQuery.ajax/

: 그렇지 않으면이 내가 잘 알고 있어요 구문은
관련 문제