如何使用在事件中声明的参数进行回调

How to callback with an argument which gets declared in event

我正在努力完成以下工作。 基本上在 onReadyStateChange 事件之后,它应该通过函数 cb() 提醒结果。虽然它似乎并没有真正起作用。它只是什么都不做。 我怎样才能完成这项工作?

谢谢。

loadDoc();
function loadDoc() {
  POST("http://foobar.com/", "POST", "{foo: bar}", cb);
}

function cb(r){
    alert(r);
}

function POST(url, method, json, callback){
var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      function x(){ callback(xhttp.responseText); }
    }
  };
  xhttp.open(method, url, true);
  xhttp.send(json);
}

非常感谢。

您不需要将回调包装在另一个函数中,只需这样做即可。

if (xhttp.readyState == 4 && xhttp.status == 200) {
  callback(xhttp.responseText);
}