programing

AJAX 응답 텍스트 반환 방법

goodjava 2023. 3. 11. 08:57

AJAX 응답 텍스트 반환 방법

프로토타입을 사용하여 AJAX 개발을 수행하고 코드를 다음과 같이 사용합니다.

somefunction: function(){
    var result = "";
    myAjax = new Ajax.Request(postUrl, {
        method: 'post',
        postBody: postData,
        contentType: 'application/x-www-form-urlencoded',
        onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
            }
        }
    });
    return result;
}

그 결과 "결과"가 빈 문자열임을 알게 되었습니다.그래서 이렇게 해봤는데

somefunction: function(){
    var result = "";
    myAjax = new Ajax.Request(postUrl, {
        method: 'post',
        postBody: postData,
        contentType: 'application/x-www-form-urlencoded',
        onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
                return result;
            }
        }
    });

}

하지만 그것 또한 효과가 없었다.다른 메서드에서 사용할 responseText를 얻으려면 어떻게 해야 합니까?

onComplete는 일부 기능이 작동한 후 한참 후에 호출됩니다.필요한 것은 콜백 함수를 파라미터로서 일부 함수에 전달하는 것입니다.이 함수는 프로세스가 완료되면 호출됩니다(즉, onComplete).

somefunction: function(callback){
    var result = "";
    myAjax = new Ajax.Request(postUrl, {
        method: 'post',
        postBody: postData,
        contentType: 'application/x-www-form-urlencoded',
        onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
                callback(result);
            }
        }
    });

}
somefunction(function(result){
  alert(result);
});

코드에 "비동기: false"를 추가하는 것은 어떨까요?저 같은 경우에는 잘 작동했습니다. :)

언급URL : https://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text