기본적으로
, $.ajax
(예 : $.post
으로 그것을 사용하는 것도,)입니다. async:false
(documentation 참조)을 지정하여 요청을 동기화할 수 있습니다. 동기 AJAX 요청을 사용하는 것은 좋지 않습니다. 성능이 저하되고 사용자 환경이 좋지 않기 때문입니다. 대신, 결과가 완료되면 성공 핸들러에서 호출되는 콜백을 사용하는 것이 좋습니다.
여기에 두 가지 임의의 간단한 예제가 있습니다. 여기에는 클릭 할 때 AJAX 호출의 결과에서 텍스트를 대체 할 앵커가 있습니다. 두 가지 모두 똑같은 일을하지만 두 번째는 브라우저의 응답 성을 유지하기 때문에 선호됩니다.
동기 :
function invokeAjaxSync() {
var text;
$.ajax({url: '/path/to/resource', async:false, success: function(result) {
text = result.toString();
}}); // will wait until this call is complete
return text;
}
$('a.example').click(function() {
$(this).text(invokeAjaxSync()); // works, but the browser will be unresponsive while waiting for a response.
});
비동기 (더 나은) :
function invokeAjaxAsync(callback) {
$.ajax({url:'/path/to/resource', success: function(result) {
callback(result);
}});
}
$('a.example').click(function() {
var $this = $(this);
invokeAjaxAsync(function(result) {
$this.text(result.toString());
}); // browser will remain responsive, but still update text when the AJAX call completes.
});
당신이 무슨 일이 일어나고 있는지 보여주기 위해 jsfiddle.net을 할 수 있나요? – JamesSwift
http://stackoverflow.com/questions/12560879/javascript-executes-before-getting-result-from-a-ajax-call의 중복 –
Ajax의 비동기 특성을 고려하여 코드를 리팩터링하는 것이 좋습니다. 일반적으로 동기식 Ajax를 사용하는 것은 잘못된 솔루션입니다. 일반적인 기술은 매개 변수로 콜백을 사용하고 Ajax 호출이 콜백을 호출하여 콜백을 반환 할 때 함수가 값을 반환하도록하는 것이 아닙니다. – nnnnnn