2016-12-29 2 views
0

내 AJAX 호출에있는 함수가 호출되는 범위에서 변수 "this"에 액세스 할 수 있기를 바랍니다. 가능한 한 많은 코딩을 피하고 싶습니다. 따라서 도움을 요청해야합니다. 그래도 몇 가지 아이디어가 있습니다.functioncall 내의 함수에 객체 전달하기

  • 콜백 호출에서 인수로 보낼 ajax 함수에 선택적 매개 변수를 추가하십시오. 그것은 꽤되지 않을 것이지만 반드시 작동 할 것입니다.
  • ajax와 함께 객체 참조를 보내고 php로 수신 한 다음 다시 보내면 응답을 통해 액세스 할 수 있습니다. 이것은 ajax 함수를 아끼지 만 엉망진창을 백엔드에 전달합니다.

// Working ajax function | The problem is below this 
 
function ajax(protocol = "GET", url = "", callback = function(response){ console.log(response); }, data = null){ 
 
\t 
 
\t // Build data 
 
\t var formData = null; 
 
\t if(data !== null){ 
 
\t \t formData = new FormData(); 
 
\t \t for(var instance in data){ 
 
\t \t \t formData.append(instance, data[instance]); 
 
\t \t } 
 
\t } 
 

 
\t // Build essential ajax components 
 
\t var xhr = new XMLHttpRequest(); 
 
\t xhr.open(protocol, url, true); 
 
\t 
 
\t // Check for state updates 
 
\t xhr.onreadystatechange = function(){ 
 
\t \t if(xhr.readyState === XMLHttpRequest.DONE){ 
 
\t \t \t if(xhr.status === 200){ 
 
\t \t \t \t callback(xhr.responseText); 
 
\t \t \t } 
 
\t \t \t else{ 
 
\t \t \t \t callback("Error code: " + xhr.status); 
 
\t \t \t } 
 
     } 
 
\t } 
 

 
\t // Send it! 
 
\t xhr.send(formData); 
 
} 
 

 

 

 
// My class 
 
function MyClass(el){ 
 
    this.target = el; 
 
    this.fetch(); // Call the fetch method 
 
} 
 
MyClass.prototype.fetch(){ 
 
    this; // "This" works perfectly in this scope as it refers to myInstance in this example 
 
    
 
    
 
    ajax("POST", "target/path.php", function(response){ 
 
    var newEl = document.createElement("div"); 
 
    newEl.innerHTML = response; 
 
    
 
    // HERE's THE RPOBLEM 
 
    this.target.appendChild(newEl); // "this" refers to the window object.. 
 
    
 
    }, {data: "data"}); 
 
} 
 

 
var myTarget = document.getElementById("myTarget"); 
 
var myInstance = new MyClass(myTarget);
<div id="myTarget"></div>

+0

가능한 중복 http://stackoverflow.com/questions/14670359/javascript -how-to-get-this-variable-in-callback-function) – skyline3000

답변

1

당신은 폐쇄

MyClass.prototype.fetch(){ 
    this; // "This" works perfectly in this scope as it refers to myInstance in this example 

    var that = this; 

    ajax("POST", "target/path.php", function(response){ 
    var newEl = document.createElement("div"); 
    newEl.innerHTML = response; 

    // HERE's THE RPOBLEM 
    that.target.appendChild(newEl); // "this" refers to the window object.. 

    }, {data: "data"}); 
} 

2)를 만들 수 있습니다

1) 문제에 대해 여러 솔루션을 사용할 수있다 bind method

MyClass.prototype.fetch(){ 
    this; // "This" works perfectly in this scope as it refers to myInstance in this example 


    ajax("POST", "target/path.php",(function(response){ 
    var newEl = document.createElement("div"); 
    newEl.innerHTML = response; 

    // HERE's THE RPOBLEM 
    this.target.appendChild(newEl); // "this" refers to the window object.. 

    }).bind(this), {data: "data"}); 
} 
1

이를 저장할 수 있습니다 : 콜백 내부

var context = this; 

, 사용 상황 ... 을이 창을 참조 귀하, 그것은 불리는 윈도우 기능 (아약스 기능) 객체에 의해. 그런데 , 당신의 코드가 잘못 (프로토 타입 DEC) :

MyClass.prototype.fetch=function(){ 
var context=this; // "This" works perfectly in this scope as it refers to myInstance in this example 
ajax("POST", "target/path.php", function(response){ 
var newEl = document.createElement("div"); 
newEl.innerHTML = response; 
// HERE's NOT THE RPOBLEM 
context.target.appendChild(newEl); // "context" refers to the MyClass Object object.. 
}, {data: "data"}); } 
[콜백 함수에서 this.variable하는 방법에 자바 스크립트 (의
+0

고마워요! 테스트하지 않고 코드를 단순화 했으므로 그 방법이 잘못되었습니다. –