programing

호출 함수에서 jquery ajax 콜백을 기다립니다.

lastcode 2023. 9. 24. 12:55
반응형

호출 함수에서 jquery ajax 콜백을 기다립니다.

이런 유형의 질문에 대한 답을 많이 검토했는데 지금은 가장 좋은 방법에 대해 혼란스럽습니다.최근의 질문을 고려할 때, 저는 다음과 같이 하고 싶습니다.

  1. 아약스 함수 호출
  2. 아약스 처리를 하다(성공 또는 오류) // 잘 작동합니다.
  3. 성공 또는 오류 시 추가 처리를 위해 상태를 호출 기능으로 되돌립니다.

호출 기능(doAjax)에서 콜백을 기다렸다가 성공 또는 오류 처리를 완료하는 방법(이 경우 성공 시 양식 삭제, 오류 시에는 그대로 유지)

어떤 조언이든 감사합니다.

예술 [EDIT] 여러분들이 발견했을 때 오타가 있었습니다, 전화는 AnAjax를 하지 말 것.

$(function () {
    doAnAjax(Url, data, function (myRtn) {
        if (myRtn == "success") {
            resetForm($('#myForm'));
            resetForm($('form[name=addChlGrp]'));
        } else {
            $('.rtnMsg').html("Opps! Ajax Error");
        }
    });
});

function doAnAjax(newUrl, data) {
    $.ajax({
        url: newUrl,
        async: true,
        dataType: 'html',
        beforeSend: function () {
            $('.rtnMsg').html("<img src=_cssStyleImg_-A-loading.gif>");
        },
        type: "GET",
        data: data,
        cache: false,
        success: function (data, textStatus, xhr) {
            $('.rtnMsg').html(data);
            myRtnA = "Success"
            return myRtnA;
        },
        error: function (xhr, textStatus, errorThrown) {
            $('.rtnMsg').html("opps: " + textStatus + " : " + errorThrown);
            myRtnA = "Error"
            return myRtnA;
        }
    });
}

콜백 기능을 사용해야 합니다.아래에서 시도해 보십시오.

$(function() {

   // I think doAjax should doAnAjax()
   // here you're passing callback
   // but you're not using it doAnAjax()

    doAnAjax(Url, data, function(myRtn) {
        if (myRtnV == "success") {
            resetForm($('#myForm'));
            resetForm($('form[name=addChlGrp]'));
        } else {
            $('.rtnMsg').html("Opps! Ajax Error");
        }
    });
});

// pass callback as third parameter to doAnAjax()

function doAnAjax(newUrl, data, callBack) {
    $.ajax({
        url: newUrl,
        async: true,
        dataType: 'html',
        beforeSend: function() {
            $('.rtnMsg').html("<img src=_cssStyleImg_-A-loading.gif>");
        },
        type: "GET",
        data: data,
        cache: false,
        success: function(data, textStatus, xhr) {
            $('.rtnMsg').html(data);
            myRtnA = "Success"
            return callBack( myRtnA );  // return callBack() with myRtna
        },
        error: function(xhr, textStatus, errorThrown) {
            $('.rtnMsg').html("opps: " + textStatus + " : " + errorThrown);
            myRtnA = "Error"
            return callBack ( myRtnA ); // return callBack() with myRtna
        }
    });

앞서 언급했듯이 콜백을 사용합니다.

function process(url, params, successCallback, errorCallback) {
    $.ajax({
        success : successCallback,
        error : errorCallback,
        data : params,
        url : url,
        type : 'POST',
        dataType : 'json'
    });
}

process(
    'http://www.google.co.uk', 
    { 
        param1 : 'a' 
    }, 
    function(resp) { 
        alert('Success');
    },
    function() {
        alert('Uh oh');
    }
);

그런 다음 모든 기능을 다음에 전달할 수 있습니다.process성공/오류 시 호출됩니다.

답은 그렇지 않다는 것이지만, 쉽게 달성할 수 있습니다.AJAX의 개념은 그것이 비동기적이기 때문에 AJAX라는 것입니다.즉, 원래 ajax를 호출하는 함수가 완료될 때까지 기다리지 않고 ajax 호출 후 완료되는 모든 작업이 성공 또는 오류 처리기에 있어야 합니다.

동기화가 필요한 경우 플래그를 다음에서 변경할 수 있습니다.async:true로.async:false그러나 그러면 실제로 SJAX 호출이 됩니다(해당 용어가 존재하는지도 모르지만 엄밀히 말하면 더 이상 AJAX 호출이 아닙니다).

jquery에서 'derferred'를 확인해보세요.아래 예제는 비동기를 끈 상태에서 derped.done을 사용하여 저에게 효과가 있는 것 같습니다.!

$.ajax({
    url: "http://www.whatever.com/whatever",
    async: false }).done(function( data ) {
        alert(data); //or whatever
    })

언급URL : https://stackoverflow.com/questions/11576176/wait-for-a-jquery-ajax-callback-from-calling-function

반응형