【问题标题】:adding attributes to XHR callback function向 XHR 回调函数添加属性
【发布时间】:2013-11-12 12:23:52
【问题描述】:

我觉得如果我知道如何调用 xhr.addEventListener (????) 的第一个属性,这可能会起作用,

var string= "I wan't to be sent as an attribute";

var xhr = new XMLHttpRequest()
xhr.addEventListener("load", uploadComplete(????, string), false)

function uploadComplete (evt, attr) {
   cosnole.log(attr);

   console.log(evt.target.responseText)
}

【问题讨论】:

    标签: javascript ajax xmlhttprequest jqxhr


    【解决方案1】:

    您可以使用一种称为currying 的技术将附加参数传递给您的回调函数。基本上,您编写一个匿名函数,该函数使用静态参数调用您的函数并将其用作回调函数。对于您的示例,这应该有效:

    function uploadComplete (evt, attr) {
       console.log( attr );
       console.log( evt.target.responseText );
    }
    
    var extra = "I want to be sent as an attribute";
    
    var xhr = new XMLHttpRequest();
    xhr.addEventListener( "load", function (evt)
        uploadComplete( evt, extra );
    }, false );
    

    匿名函数由事件系统调用,并调用您的uploadComplete 函数,传递它作为参数接收的事件对象和extra 的值,它通过closure 访问。如果 extra 变量在您定义回调函数时在范围内,则无需将其作为参数传递;你可以通过回调的闭包来访问它。

    var extra = "I want to be sent as an attribute";
    
    function uploadComplete (evt) {
       console.log( extra );
       console.log( evt.target.responseText );
    }
    
    var xhr = new XMLHttpRequest();
    xhr.addEventListener( "load", uploadComplete, false );
    

    还请注意,当您传递要用作回调的函数时,您只需使用不带括号的函数名称。如果您使用括号,则您自己调用该函数并将其返回值作为回调传递。

    【讨论】:

      猜你喜欢
      • 2017-08-26
      • 2012-01-25
      • 1970-01-01
      • 2012-04-05
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多