반응형
Ajax 내부의 Javascript 변수에 액세스 성공
var flag = false; //True if checkbox is checked
$.ajax({
... //type, url, beforeSend, I'm not able to access flag here
success: function(){
// I'm not able to access flag here
}
});
Ajax 내부에서, 만약 내가 접속을 시도한다면.flag
정의되지 않았다고 합니다.아약스 함수 안에서 어떻게 사용할 수 있습니까?
감 잡히는 게 없어요?
플래그와 아약스는 모두 함수의 본문입니다.이 함수에는 다른 항목이 없습니다.
참조를 통해 변수를 만들면 변수에 액세스할 수 있습니다.Javascript의 모든 개체는 참조된 값이지만 기본 값은 그렇지 않습니다(예: int, string, bool 등).
따라서 플래그를 개체로 선언할 수 있습니다.
var flag = {}; //use object to endure references.
$.ajax({
... //type, url, beforeSend, I'm not able to access flag here
success: function(){
console.log(flag) //you should have access
}
});
또는 성공 함수에 원하는 매개 변수를 지정합니다.
var flag = true; //True if checkbox is checked
$.ajax({
... //type, url, beforeSend, I'm not able to access flag here
success: function(flag){
console.log(flag) //you should have access
}.bind(this, flag) // Bind set first the function scope, and then the parameters. So success function will set to it's parameter array, `flag`
});
여기 한 가지 방법이 있습니다.beforeSend 콜백 옵션을 사용하면 jqXHR 개체와 ajax 설정 개체에 모두 액세스할 수 있습니다.
caturl은 요청 던지기 오류와 동기화되지 않기 때문에 오류 추가에 사용할 수 없습니다.
$.ajax({
/* url, data ...& other opts*/
beforeSend:function( jqXHR, settings){
/* add url property and get value from settings (or from caturl)*/
jqXHR.url= settings.url;
},
/* error to be deprecated in jQuery 1.8 , superseded by "fail" */
error: function(jqXHR, , textStatus, error){
var url=jqXHR.url;
/* replace caturl with url in your append */
$('#showdata').prepend("ERROR : '" + error + "' trying to access: " + url + "</br>");
}
언급URL : https://stackoverflow.com/questions/30734372/access-javascript-variable-inside-ajax-success
반응형
'source' 카테고리의 다른 글
Spring MVC의 Ajax 요청에서 세션 시간 초과 탐지 (0) | 2023.08.27 |
---|---|
그리드 보기 행 명령에서 데이터 키 값 가져오기 (0) | 2023.08.27 |
url 매개 변수를 javascript/jquery로 대체하는 방법은 무엇입니까? (0) | 2023.08.27 |
git 기록에서 병합 커밋 제거 (0) | 2023.08.27 |
jQuery의 mouse out()과 mouse leave()의 차이점은 무엇입니까? (0) | 2023.08.27 |