반응형
jQuery / Ajax - $.ajax() 콜백에 매개 변수 전달 - 사용하기 좋은 패턴?
시작하는 JavaScript 코드:
function doSomething(url) {
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: rssToTarget
});
}
사용하고 싶은 패턴:
//where elem is the target that should receive new items via DOM (appendChild)
function doSomething(url, elem) {
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: rssToTarget(elem)
});
}
이런 식으로는 콜백이 안 될 것 같죠?올바른 패턴은 무엇입니까?글로벌 변수를 반드시 사용하여 일시적으로 보류하고 싶지는 않습니다.elem
또는 elem name 입니다.
이렇게...
function doSomething(url, elem) {
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: function(xml) {
rssToTarget(xml, elem);
}
});
}
코멘트에 대한 답변:익명 기능의 사용은 퍼포먼스에 영향을 미칩니까?
rssToTarget 함수 내에 닫힘을 생성하면 사용할 수 있는 패턴입니다.
function rssToTarget(element) {
return function (xmlData) {
// work with element and the data returned from the server
}
}
function doSomething(url, elem) {
$.ajax({ type: "GET",
url: url,
dataType: "xml",
success: rssToTarget(elem)
});
}
언제rssToTarget(elem)
이 실행되면 요소 파라미터가 클로저에 저장되고 콜백 함수가 실행 대기 상태로 반환됩니다.
Ajax 요청 설정 컨텍스트를 설명하는 것은 어떻습니까?
function doSomething(url, elem) {
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: rssToTarget,
elem: elem // <- add as settings argument
});
}
rssToTarget(ans) {
elem = this.elem; // <- get it back using "this"
}
디폴트로는 콜백콘텍스트는$.ajaxSettings
및 설정 전달$.ajax
에 필드를 추가하면$.ajax
콜백 컨텍스트에 들어갑니다.즉, 다음 명령어를 사용하여 컨텍스트에서 취득할 수 있습니다.this
.
언급URL : https://stackoverflow.com/questions/1194104/jquery-ajax-ajax-passing-parameters-to-callback-good-pattern-to-use
반응형
'programing' 카테고리의 다른 글
URL에 JSON 콜을 발신하는 방법 (0) | 2023.03.09 |
---|---|
스프링 부트에서의 여러 Web Security Configurer Adapter 사용 (0) | 2023.03.09 |
'wp_module'이 작동하지 않습니다. (0) | 2023.03.09 |
특정 제품 카테고리에 따른 WooCommerce 체크아웃 메시지 (0) | 2023.03.04 |
외부 템플릿에서 $compile 사용(템플릿)URL)의 각도 지시어 (0) | 2023.03.04 |