微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript XMLHttpRequest 行为怪异

如何解决Javascript XMLHttpRequest 行为怪异

我有以下代码向我在 MysqL 中设置的表添加“订单”。我将它作为一个或多个 POST 请求发送到后端。

这个想法是我发送第一个 POST 请求,将一个 customerID 和一个 galleryID 添加MysqL,然后创建一个新的“订单”并添加这些项目。它还将它添加到我设置的名为 OrdersTogalleries 的 many:many 表中

然后我遍历剩余的paintingID 并发送POST 请求。这些请求将在 orders 表中查询最近的订单,然后将 customerID 和 galleryID 添加到 OrdersTogalleries 表中。

出于某种原因,它似乎最多只能发送三个请求,然后随机崩溃大约 4 个或更多。

我想我的主要问题是,我可以像这样执行多个发布请求吗?或者这是导致我的错误?我以前没有尝试过在循环内进行发布请求。

以下是我的代码,感谢您的帮助:

    //Button to add a gallery to our table
var addButton = document.createElement("button");
var addButtonText = document.textContent = "Submit";
addButton.appendChild(document.createTextNode(addButtonText));
document.getElementById("orderAdderButton").appendChild(addButton);

//When client clicks the add a gallery submit button:
function addButtonClick() {
  var req = new XMLHttpRequest(); //create new request

  //get the values entered by user
  var payloadCustomerID = document.getElementById("customerIDForm").value;
  var payloadPaintingIDinitial = document.getElementById("paintingsIDForm").value;


  //if one of the items in the table is not filled out,display error about that item
  //(after this,it will check all items are filled in. If not,it will error and not add to table)
  if (payloadCustomerID == undefined || payloadCustomerID == "") {
    document.getElementById("addErrorNameCustomerID").textContent = "ERROR: Missing customer ID";
    event.preventDefault();
  } else document.getElementById("addErrorNameCustomerID").textContent = "";
  if (payloadPaintingIDinitial == undefined || payloadPaintingIDinitial == "") {
    document.getElementById("addErrorPaintingsID").textContent = "ERROR: Missing paintingID";
    event.preventDefault();
  } else document.getElementById("addErrorPaintingsID").textContent = "";

  //remove any whitespace characters
  payloadPaintingIDinitial.replace(/ /g,"");
  //split the string into numbers by splitting it
  var payloadPaintingID = payloadPaintingIDinitial.split(",");

  //stuff to send to the POST request
  var payload = {};
  payload.payloadCustomerID = payloadCustomerID;
  payload.payloadPaintingID = payloadPaintingID;


  //check if all (required) items are fileld out. If so,continue on sending the data to the database,else display error and don't do anything
  if (payloadCustomerID != "" && payloadPaintingID[0] != "") {


    //SEND INITIAL ORDER (CREATES A NEW ORDER AND ADDS FirsT PAINTING)
    //send an insert request to our server via GET
    req.open("POST","http://flip1.engr.oregonstate.edu:" + port + "/orders",true);

    //for post request,set the header:
    req.setRequestHeader('Content-Type','application/json');

    //add event listener for async request (function)
    req.addEventListener('load',function () {
      console.log("Adding order request status: " + req.status); //for testing
      if (req.status >= 200 && req.status < 400) {
        //if request send is good do this:
        console.log("Success in adding order");
      } else { //if error:
        console.log("Error in network request: " + req.statusText);
        if (req.status === 409) //bad customer request:
        {
          alert("Invalid Customer ID given,please try again.");
          return;
        }
        else if (req.status === 400) //gallery ID not found
        {
          alert("Invalid Painting ID given,please try again.");
          return;
        }
        event.preventDefault();
      }
    });

    event.preventDefault();
    //send the request
    req.send(JSON.stringify(payload));
    event.preventDefault();


    //add in any extra paintings to new order number
    for (var i = 1; i < payloadPaintingID.length; i++) {

      var req2 = new XMLHttpRequest();
      payload.currentPayloadPaintingID = payloadPaintingID[i];

      //send an insert request to our server via GET
      req2.open("POST","http://flip1.engr.oregonstate.edu:" + port + "/moreOrders",true);

      //for post request,set the header:
      req2.setRequestHeader('Content-Type','application/json');

      //add event listener for async request (function)
      req2.addEventListener('load',function () {
        console.log("Adding order request status: " + req2.status); //for testing
        if (req2.status >= 200 && req2.status < 400) {
          //if request send is good do this:
          console.log("Success in adding order");
        } else { //if error:
          console.log("Error in network request: " + req2.statusText);
          if (req2.status === 409) //bad customer request:
          {
            alert("Invalid Customer ID given,please try again.");
            event.preventDefault();
            window.location.replace('./orders');
            return;
          }
          else if (req2.status === 400) //gallery ID not found
          {
            alert("Invalid Painting ID given,please try again.\n NOTE: Paintings before this ID were added successfully");
            event.preventDefault();
            window.location.replace('./orders');
            return;
          }
          event.preventDefault();
        }
        event.preventDefault();
      });

      //send the request
      req2.send(JSON.stringify(payload));
    }
  }
  alert("Painting(s) added successfully to order");
  event.preventDefault();
  window.location.replace('./orders');
  return;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。