JavaScript XMLHttprequests

标签 javascript ajax xmlhttprequest

我从第 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/

相关文章:

Javascript AddEventListener 未定义

javascript - 如何检查 HTTP 请求是否在浏览器中打开?

javascript - 当用户单击时关注自定义元素并在其后面创建覆盖层

javascript - orderBy 带有下拉列表的嵌套排序正在对数据进行分组

javascript - 使用ajax和json将数组从php发送到js

javascript - 主线程上的同步 XMLHttpRequest 已被弃用,因为它会对最终用户的体验产生不利影响

javascript - 接口(interface)将键值限制为 const Typescript 的精确值

javascript - Firebug - 如何运行多行脚本或创建新的 JavaScript 文件?

javascript - 如何在点击链接时执行 Ajax 代码?

php - 单击动态创建的复选框时通过 AJAX/PHP 更新 MySQL 中的值?