gpt4 book ai didi

JavaScript XMLHttprequests

转载 作者:行者123 更新时间:2023-11-30 10:50:52 25 4
gpt4 key购买 nike

我从第 275 页的 Stoyan Stefanovs Object Oriented JavaScript 那里得到了这个演示 AJAX 的例子。在这个例子中,他请求三个不同的文件。如果你们中有人可以提供帮助,我有几个问题。

  1. xhr.send('') 在做什么?我们为什么需要它?我以为之前行中的 GET 是与服务器建立联系,所以为什么要发送?
    (其他问题涉及闭包,我不是很懂...)

  2. 究竟将什么作为参数传递给 function(myxhr)

  3. 关于将 (xhr) 作为参数传递的匿名函数,您能否解释一下程序中的什么时候将 xhr 传递给匿名函数?例如,是在 xhr.open 发生之后吗?

  4. 为什么需要 function(myxhr)?如果要创建闭包,为什么这里需要闭包?

  5. 是匿名函数的参数(xhr),一旦匿名函数被作为参数myxhr传递给function(myxhr)叫什么?

  6. 如果 5 为真——xhr 作为参数传递给 function(myxhr)——为什么需要将参数名称从xhrmyxhr?

示例代码:

function request(url, callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = (function(myxhr){
return function() {
callback(myxhr);
}
})(xhr);
xhr.open('GET', url, true);
xhr.send('');
}

request (
'http://www.phpied.com/files/jsoop/content.txt',
function (o){
document.getElementById('text').innerHTML = o.responseText;
}
);

request(
'http://www.phpied.com/files/jsoop/content.html',
function(o) {
document.getElementById('html').innerHTML = o.responseText;
}
);

request(
'http://www.phpied.com/files/jsoop/content.xml',
function(o){
document.getElementById('xml').innerHTML =
o.responseXML.getElementsByTagName('root')[0].firstChild.nodeValue;
}
);

最佳答案

What is xhr.send('') doing? Why do we need it? I thought GET in the line before was establishign contact with the server, so why this send? (The other questions relate to the closure that I don`t fully understand...)

Open只是建立请求。发送实际发送它。当您发出 POST 请求时,您需要传递 to send。

what exactly is getting passed as a paramater to function(myxhr)?

变量的内容xhr .

regarding the anonymous function, which has (xhr) passed as a parameter, can you explain at what point in the program xhr gets passed to the anonymous function? For example, is it after xhr.open has taken place?

一旦函数被调用(当定义后紧跟着 () 时)。

why is function(myxhr) necessary? If it`s to create closure, why is closure necessary here?

事实并非如此。即使 xhr变量未在本地作用域内 request函数(它是)然后可以通过 this 访问它.

is parameter (xhr) of the anonymous function getting passed as parameter myxhr in function(myxhr) once the anonymous function is called?

是的。

if 5 is true--that xhr is passed as a parameter to function(myxhr)--why is it necessary to change the parameter name from xhr to myxhr?

事实并非如此。您可以在不同的范围内重复使用变量名称。不过,它减少了混淆。

关于JavaScript XMLHttprequests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5401756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com