简体   繁体   English

XMLHttpRequest 有时不起作用

[英]XMLHttpRequest does not working sometimes

I've created a ClickListener which is supposed to make a POST request to my server.我创建了一个ClickListener ,它应该向我的服务器发出POST请求。 Most of the times, the POST request is made but sometimes, it fails to make a POST request no matter how many times I try.大多数情况下,发出 POST 请求,但有时,无论我尝试多少次,它都无法发出POST请求。 Can anyone help me understand what the issue is and how to resolve it?任何人都可以帮助我了解问题是什么以及如何解决它? This is my code where I'm handling that:这是我正在处理的代码:

$("#Button11").on("click", function() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/addtolist", true);
  xhr.setRequestHeader(
    "Content-type",
    "application/x-www-form-urlencoded",
    "Access-Control-Allow-Origin",
    "*"
  );
  var parameter = "dc=deal1";
  xhr.send(parameter);
  window.location.href = "/final_page.ejs";
});

The issue问题

XMLHttpRequest.send() is an asynchronous method, that mean this method only ask the request to be sent but it will not be done instantly. XMLHttpRequest.send()是一种异步方法,这意味着该方法只要求发送请求,但不会立即完成。 Most of the time, this does not matters, but in your script, you redirect the user right after it, so, sometime, the user is redirected before the request is sent.大多数情况下,这并不重要,但在您的脚本中,您会在它之后立即重定向用户,因此,有时,用户会在发送请求之前被重定向。

The solution解决方案

You have to wait the request to be done before redirecting the user, thankfully, XMLHttpRequest have a method to achieve it.在重定向用户之前,您必须等待请求完成,谢天谢地, XMLHttpRequest有一种方法可以实现它。 It is the XMLHttpRequest.onload() method.它是XMLHttpRequest.onload()方法。 So you can update your script to :因此,您可以将脚本更新为:

$("#Button11").on("click", function() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/addtolist", true);
  xhr.setRequestHeader(
    "Content-type",
    "application/x-www-form-urlencoded",
    "Access-Control-Allow-Origin",
    "*"
  );
  var parameter = "dc=deal1";
  xhr.send(parameter);
  xhr.onload = function(){
    window.location.href = "/final_page.ejs";
  };
});

As mentioned in the comments, JQuery also have an integrated solution for making request, I recommend you reading it's documentation to have an even better solution.正如评论中提到的,JQuery 也有一个用于发出请求的集成解决方案,我建议您阅读它的文档以获得更好的解决方案。

Your location change is killing your Ajax before it finishes您的位置更改在完成之前杀死了您的 Ajax

Also why not use the much simpler $.post now you have it?另外为什么不使用更简单的 $.post 现在你有了它?

None of your headers are needed and the auth header is not even allowed to be set by you不需要您的任何标头,甚至不允许您设置 auth 标头

$("#Button11").on("click", function() {
  $.post("/addtolist",{"dc":"deal1"},function() {
    window.location.href = "/final_page.ejs";
  })  
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM