最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing extra arguments to XMLHttpRequest.onload - Stack Overflow

programmeradmin5浏览0评论

I'm trying to unicate with a server, using XMLHttpRequest in javascript.

How can I pass info to the onload function?

// global variable that containts server response
var reply;

var makeRequest = function(extraInfo) {
  var request = new XMLHttpRequest();
  request.open(...);
  request.onload = handler;
};

var handler = function(data) {
  reply = data.target.response;
  console.log("Server Reply: " + reply);
};

How can I pass the parameter extraInfo from makeRequest to the handler function? (without using a global variable)

I'm trying to unicate with a server, using XMLHttpRequest in javascript.

How can I pass info to the onload function?

// global variable that containts server response
var reply;

var makeRequest = function(extraInfo) {
  var request = new XMLHttpRequest();
  request.open(...);
  request.onload = handler;
};

var handler = function(data) {
  reply = data.target.response;
  console.log("Server Reply: " + reply);
};

How can I pass the parameter extraInfo from makeRequest to the handler function? (without using a global variable)

Share Improve this question asked Dec 28, 2016 at 10:14 TirafesiTirafesi 1,4793 gold badges19 silver badges39 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Just use a closure in such way:

...
var makeRequest = function(extraInfo) {
    var request = new XMLHttpRequest();
    request.open(...);
    request.onload = function(data) {
        // extraInfo is accessible here
        reply = data.target.response;
        console.log("Server Reply: " + reply);
    };
};

I figured out that passing extra info into the request handler can be done this way: (At least is good for me)

    request.open(...);
    request.extraInfo = identifier;
    request.onload = function() {
        identifier = this.extraInfo;
    };

The accepted solution didn't work for me, but this did

const params = new FormData();
params.append('selectedValue', selectedValue);
const xhr = new XMLHttpRequest();
xhr.open('post', url, true);
xhr.send(params);
xhr.extraInfo = extraInfo;   // <- set your data here
xhr.onload = (e) => {
    const data = JSON.parse(xhr.responseText);

    alert(xhr.extraInfo)   /// <- access it like this
    alert(e.target.extraInfo)  // <- or like this
    //return data;
};
发布评论

评论列表(0)

  1. 暂无评论