jQuery Ajax 성공 콜백 함수 정의
jQuery ajax를 사용하여 서버에서 데이터를 검색하고 싶습니다.
.ajax()
다음과 같이 성공 콜백 함수 정의를 블록 외부에두고 싶습니다. 그렇다면 dataFromServer
성공 콜백에서 반환 된 데이터를 사용할 수 있도록 다음과 같은 변수를 선언해야 합니까?
대부분의 사람들이 .ajax()
블록 내에서 성공 콜백을 정의하는 것을 보았습니다 . 외부에서 성공 콜백을 정의하려는 경우 다음 코드가 정확합니까?
var dataFromServer; //declare the variable first
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData(dataFromServer)
})
}
function handleData(data) {
alert(data);
//do some stuff
}
다음을 사용하십시오.
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
이 success
속성에는 함수에 대한 참조 만 필요하며 데이터를이 함수에 매개 변수로 전달합니다.
handleData
방법 handleData
이 선언 되었기 때문에 이와 같이 함수에 액세스 할 수 있습니다 . JavaScript는 코드를 실행하기 전에 함수 선언을 구문 분석하므로 실제 선언 이전의 코드에서 함수를 사용할 수 있습니다. 이것은 호이 스팅 으로 알려져 있습니다 .
하지만 다음과 같이 선언 된 함수에는 포함되지 않습니다.
var myfunction = function(){}
통역사가 통과 한 경우에만 사용할 수 있습니다.
함수를 선언하는 두 가지 방법에 대한 자세한 내용은이 질문을 참조하십시오.
jQuery 1.5 (2011 년 1 월)부터이 작업을 수행하는 "새로운"방법은 success
콜백 을 전달하는 대신 지연된 객체를 사용하는 것입니다 . 당신은해야 반환 의 결과를 $.ajax
다음을 사용 .done
, .fail
콜백을 추가하는 등의 방법으로 의 외부 $.ajax
전화 .
function getData() {
return $.ajax({
url : 'example.com',
type: 'GET'
});
}
function handleData(data /* , textStatus, jqXHR */ ) {
alert(data);
//do some stuff
}
getData().done(handleData);
이렇게 하면 AJAX 처리에서 콜백 처리가 분리 되어 원래 getData()
함수 를 수정할 필요없이 여러 콜백, 실패 콜백 등을 추가 할 수 있습니다 . 나중에 완료 할 일련의 작업에서 AJAX 기능을 분리하는 것은 좋은 일입니다! .
지연은 또한 여러 비동기 이벤트를 훨씬 쉽게 동기화 할 수 있도록합니다. success:
For example, I could add multiple callbacks, an error handler, and wait for a timer to elapse before continuing:
// a trivial timer, just for demo purposes -
// it resolves itself after 5 seconds
var timer = $.Deferred();
setTimeout(timer.resolve, 5000);
// add a done handler _and_ an `error:` handler, even though `getData`
// didn't directly expose that functionality
var ajax = getData().done(handleData).fail(error);
$.when(timer, ajax).done(function() {
// this won't be called until *both* the AJAX and the 5s timer have finished
});
ajax.done(function(data) {
// you can add additional callbacks too, even if the AJAX call
// already finished
});
Other parts of jQuery use deferred objects too - you can synchronise jQuery animations with other async operations very easily with them.
I do not know why you are defining the parameter outside the script. That is unnecessary. Your callback function will be called with the return data as a parameter automatically. It is very possible to define your callback outside the sucess:
i.e.
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
function handleData(data) {
alert(data);
//do some stuff
}
the handleData function will be called and the parameter passed to it by the ajax function.
Try rewriting your success handler to:
success : handleData
The success property of the ajax method only requires a reference to a function.
In your handleData function you can take up to 3 parameters:
object data
string textStatus
jqXHR jqXHR
I would write :
var handleData = function (data) {
alert(data);
//do some stuff
}
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
after few hours play with it and nearly become dull. miracle came to me, it work.
<pre>
var listname = [];
$.ajax({
url : wedding, // change to your local url, this not work with absolute url
success: function (data) {
callback(data);
}
});
function callback(data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
// $('#displayImage1').append( "<img src='" + wedding + val +"'>" );
listname.push(val);
}
});
}
function myfunction() {
alert (listname);
}
</pre>
You don't need to declare the variable. Ajax success function automatically takes up to 3 parameters: Function( Object data, String textStatus, jqXHR jqXHR )
In your component i.e angular JS code:
function getData(){
window.location.href = 'http://localhost:1036/api/Employee/GetExcelData';
}
참고URL : https://stackoverflow.com/questions/14754619/jquery-ajax-success-callback-function-definition
'programing tip' 카테고리의 다른 글
Docker 오류 : 클라이언트와 서버의 버전이 동일하지 않습니다. (0) | 2020.09.21 |
---|---|
경고 : 숫자가 아닌 값이 발견되었습니다. (0) | 2020.09.20 |
FormData에 배열을 추가하고 AJAX를 통해 전송 (0) | 2020.09.20 |
Python3 : ImportError : 모듈 다중 처리의 값을 사용할 때 '_ctypes'라는 모듈이 없습니다. (0) | 2020.09.20 |
UITextField에서 Swift 추가 아이콘 / 이미지 (0) | 2020.09.20 |