如何将数据库中的数据分配给全局变量

时间:2019-04-25 12:10:07

标签: javascript ajax

我试图将外键包含在从数据库获得的表中,我想出的解决方案之一是获取所有数据并将它们存储在全局变量中,然后在需要的地方使用。

我尝试在当前get范围内使用一个get方法,尽管我确信这不是最好的方法,因为根据调用的表,我将获得2-3次相同的数据。

我遇到的错误是:

  

“ js.js:205未捕获的TypeError:无法设置未定义的属性'R1000002'”的第205行位于第一个代码段("fk_RouteStations[element.ROUTE_ID] = element;"

params = {
  headers: {
    "content-type": "application/json; charset=UTF-8",
    "Access-Control-Allow-Origin": "*"
  }
}

$.ajax({
  url: "...",
  type: "GET",
  data: params,
  success: function(result) {
    result.forEach(function(element) {
      fk_RouteStations[element.ROUTE_ID] = element;
    })
    console.log("Got ROUTE_STATIONS Data");
  }
}).fail(console.log("Failed to get ROUTE_STAITONS Data"));
//foreign keys
var fk_customer;
var fk_trains;
var fk_routes;
var fk_tickets;
var fk_carriages;
var fk_RouteStations;
var fk_staff;
var fk_stations;
else if (currentTable == "ROUTES") {
  var url = '...';
  var id = document.getElementById("searchField").value;
  const URL = url.concat(id);

  const params = {
    headers: {
      "content-type": "application/json; charset=UTF-8",
      "Access-Control-Allow-Origin": "*"
    }
  };

  console.log("Getting Routes Data");

  $.ajax({
    url: URL,
    type: "GET",
    data: params,
    success: function(result) {

      $("resultsDisplay").text("Got Results");
      //var fk_routes = JSON.stringify(result);
      var string = "<table><tr><th>ID</th><th>Price Per Stop</th><th>Route_stations</th><th>Tickets</th><th>Trains</th></tr>";
      console.log("Running results")

      if (id == "") {
        console.log("Displaying results as array");
        for (i = 0; i < result.length; i++) {
          string += "<tr><td>" + result[i].ROUTE_ID + "</td><td>" + result[i].PRICEPERSTOP + "</td></tr>";
        }

        string += "</table>";
        document.getElementById("tables").innerHTML = string;
        document.getElementById("loadingPrompt").style.display = "none";
      } else {
        console.log("Displaying results as object")
        string += "<tr><td>" + result.ROUTE_ID + "</td><td>" + result.PRICEPERSTOP + "</td><td>" + fk_RouteStations[element].ROUTE_ID + "</td><td>" + "fk_tickets[0,1]" + "</td><td>" + "TRAINS" + "</td></tr>";
        string += "</table>";
        document.getElementById("tables").innerHTML = string;
        document.getElementById("loadingPrompt").style.display = "none";
      }

      makeSelectable();
    }
  }).fail(function() {
    document.getElementById("tables").innerHTML = "User not found";
  });

期望的输出将使表正确显示外键。

0 个答案:

没有答案