내 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>
가능한 중복 http://stackoverflow.com/questions/14670359/javascript -how-to-get-this-variable-in-callback-function) – skyline3000