我希望位于我的ajax调用中的函数能够访问调用范围内的变量“this”。我想避免尽可能多的硬编码,因此我不得不寻求帮助。这里有一些想法。将对象传递给函数调用中的函数
- 在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>
[JavaScript的如何获得在回调函数this.variable](可能的重复http://stackoverflow.com/questions/14670359/javascript如何获得这个变量在回调函数) – skyline3000