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

Javascript 如何使用在事件中声明的参数进行回调,javascript,xmlhttprequest,Javascript,Xmlhttprequest,我正在努力做以下工作。 基本上,在onReadyStateChange事件之后,它应该通过函数cb()警告结果。虽然它似乎真的不起作用。这根本没用。 我怎样才能做到这一点 多谢各位 loadDoc(); function loadDoc() { POST("http://foobar.com/", "POST", "{foo: bar}", cb); } function cb(r){ alert(r); } function POST(url, method, json, ca

我正在努力做以下工作。 基本上,在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);
}

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

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

您从未调用函数
x
。为什么要将对回调的调用放在
x
中?您从未调用函数
x
。为什么要将对回调的调用放在
x
中?