Jquery Ajax 이전 전송 및 성공, 오류 및 완료
여러 개의 Ajax 함수에 문제가 있습니다.beforeSend두 번째 Ajax 포스트가 실행되기 전에complete첫 번째 아약스의 함수.
보내기 전에 플레이스 홀더에 추가하는 로드 클래스가 첫 번째 에이잭스 호출에 대해 작동합니다.단, 첫 번째 Ajax 요구가 완료된 직후 클래스는 삭제되고 두 번째 이후의 콜에서는 다시 추가되지 않습니다(재귀 콜을 기억하십시오.
디버깅 중에 디버깅을 하면beforeSend두 번째 Ajax 콜의 함수는 첫 번째 콜과complete첫 번째 Ajax 콜의 함수는 나중에 호출됩니다.첫 번째 Ajax 콜에서 페이지에 삽입된 리턴 데이터가 두 번째 콜을 시작하기 때문에 이는 명백합니다.
한마디로 뒤죽박죽이다.이 문제를 해결할 방법이 없을까요?
기능 코드는 다음과 같습니다.
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        $(placeholder).removeClass('loading');
    },
    dataType: 'html'
});
}
 
그리고 이 데이터에는 다음 javascript/jquery 조각이 포함되어 있습니다.이 조각은 다른 ajax 요청을 체크하고 시작합니다.
<script type="text/javascript">//<!--
 $(document).ready(function() {
    $('#restart').val(-1)
    $('#ajaxSubmit').click();
});
//--></script>
다음의 조작을 실시해 주세요.
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}
 
이렇게 하면beforeSend스테이트먼트가 호출되기 전에complete진술i0보다 크므로 클래스는 삭제되지 않습니다.마지막 콜만 삭제할 수 있습니다.
테스트할 수 없습니다, 동작 여부를 알려 주세요.
jQuery의 약속 API를 사용하면 훨씬 쉬워집니다.
$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )
 
또는 다음 중 하나를 전달할 수 있습니다.bind각 결과 콜백으로 기능합니다.파라미터의 순서는 다음과 같습니다.(success, failure)하나 이상의 매개 변수를 사용하여 함수를 지정하면 응답에 액세스할 수 있습니다.예를 들어, 응답 텍스트를 체크하는 경우는, 다음의 조작을 실시할 수 있습니다.
$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401
언급URL : https://stackoverflow.com/questions/21648356/jquery-ajax-beforesend-and-success-error-complete
'programing' 카테고리의 다른 글
| 스프링 부트 ddl 자동 제너레이터 (0) | 2023.04.06 | 
|---|---|
| 단일 투고에서 Wordpress 카테고리 가져오기 (0) | 2023.04.06 | 
| 번들 유효한 메시지를 표시해도 Webpack-dev-server가 번들되지 않음 (0) | 2023.04.06 | 
| Django 1.9에서 JSONFiled(네이티브 포스트그레스 jsonb)를 사용하는 규약은 무엇입니까? (0) | 2023.04.06 | 
| 각도 JS 수집되지 않은 오류: [$injector: modulerr] (0) | 2023.04.01 |