将额外的参数传递给XMLHttpRequest.onload

时间:2016-12-28 10:14:16

标签: javascript xmlhttprequest

我正在尝试与服务器通信,在javascript中使用XMLHttpRequest。

如何将信息传递给onload函数?

// 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);
};

如何将参数extraInfo从makeRequest传递给处理函数? (不使用全局变量)

3 个答案:

答案 0 :(得分:3)

以这种方式使用闭包:

...
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);
    };
};

答案 1 :(得分:1)

我发现可以通过以下方式将额外信息传递到请求处理程序 :(至少对我有好处)

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionViwe: UICollectionView!

    let dataSource = [1,2,3,4,5,6,7,8,9]

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionViwe.isPagingEnabled = true
        collectionViwe.register(Cell.self, forCellWithReuseIdentifier: "Cell")
        // Do any additional setup after loading the view.
    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
        let text = String(dataSource[indexPath.row])
        if cell.label.text != text {
            cell.label.text = text
            cell.label.backgroundColor = .random()
        }

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return view.frame.size
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return .zero
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.reloadData()
    }

}

class Cell: UICollectionViewCell {

    let label = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        label.backgroundColor = .red
        addSubview(label)
        label.frame = CGRect(x: 36, y: 36, width: 200, height: 100)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


extension CGFloat {
    static func random() -> CGFloat {
        return CGFloat(arc4random()) / CGFloat(UInt32.max)
    }
}

extension UIColor {
    static func random() -> UIColor {
        return UIColor(red:   .random(),
                       green: .random(),
                       blue:  .random(),
                       alpha: 1.0)
    }
}

答案 2 :(得分:0)

可接受的解决方案对我不起作用,但这确实有用

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;
};