XMLHttpRequest函数仅在上次调用中返回数据

我的问题是

我做了一个javascript函数,使用XMLHttpRequest通过POST方法从数据库中获取了一些数据,如果我仅使用此函数一次,则可以按我的方式工作,但是我需要在项目中以及在何时调用此函数超过1次我打电话两次或更多次,只有最后一个请求给我一些数据,第一个只显示POST方法的主体,但不返回数据,所以问题是...

每次调用时如何使该功能起作用?

如果你们能告诉我为什么现在会这样,我也将不胜感激

我将日志放入函数中以查看发生了什么情况,并且每次都可以看到POST方法请求的正文,但是只有最后一个函数会获取返回的数据,其他函数甚至会返回某些信息...

我的功能:

var xhr = new XMLHttpRequest();

function getListOfProducts(id, paramsCat, paramsSubcat, insertCheckout) {
  var params1 = {
    id_categoria: paramsCat,
    id_subcategoria: paramsSubcat,
    slug: "",
  };
  console.log(params1);

  xhr.open("POST", url);
  xhr.onload = function () {
    console.log("Loaded");
    var parse = JSON.parse(xhr.response);
    var products = parse.results;
    console.log(products);
  };
  xhr.send(JSON.stringify(params1));
}
评论
杨柳清风
杨柳清风

As suggested, You can use fetch. In existing code, Create XMLHttpRequest object every time you call getListOfProducts. Since you have same instance of xhr. So this won't work on the next call.

function getListOfProducts(id, paramsCat, paramsSubcat, insertCheckout) {
  var xhr = new XMLHttpRequest();
  //... rest of the code
}

提取中的类似代码:

function getListOfProducts(id, paramsCat, paramsSubcat, insertCheckout) {
  var params1 = {
    id_categoria: paramsCat,
    id_subcategoria: paramsSubcat,
    slug: "",
  };
  fetch({
    url: url,
    body: JSON.stringify(params1),
    method: "POST",
  })
    .then((res) => res.json())
    .then((res) => {
      var products = res.results;
      console.log(products);
    });
}
点赞
评论
Bill
Bill

像这样尝试:

xhr.open("POST", url, false);

The problem you're having is that you're firing multiple asynchronous calls. xhr calls by default are asynchronous. Including the above false flag will make it run serially along single or multiple requests.

More info here.

- 编辑

As pointed out the synchronous xhr has been deprecated.

点赞
评论