【问题标题】:Js - same class calling method on onreadystatechange XMLHttpRequest Uncaught ReferenceError: functionis not definedJs - onreadystatechange XMLHttpRequest Uncaught ReferenceError上的相同类调用方法:未定义函数
【发布时间】:2019-02-16 09:14:03
【问题描述】:
export class PizzaController{

    static loadData(){
        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            dynamicSelect(xhttp.responseXML);
          }
        };     
        xhttp.open("GET", "js/data/pizzadata.xml", true);
        xhttp.send();
    }

    dynamicSelect(xmlDoc){
        var doughTypes = [];

        let selects = document.getElementById("selects");

        let doughSelect = document.createElement("select");
        doughSelect.setAttribute("id","dough");
        selects.appendChild(doughSelect);

        let typeSelect = document.createElement("select");
        typeSelect.setAttribute("id","type");
        selects.appendChild(typeSelect);

        let toppingSelect = document.createElement("select");
        toppingSelect.setAttribute("id","topping");
        selects.appendChild(toppingSelect);    


        let x = xmlDoc.getElementsByTagName('DOUGH');
    }
}

我试图从 XML 文件中提取数据并在 webapp 上创建一个动态选择器。代码在程序化时有效,即不是“OOP”,但是我必须这样做。 PizzaController 类由 init.js 调用,而我只调用 loadData。当我尝试控制台日志时,它显示了结果,因此调用有效,因此这一定是唯一的问题。 我不断收到此错误

Uncaught ReferenceError: dynamicSelect is not defined
    at XMLHttpRequest.xhttp.onreadystatechange 

【问题讨论】:

  • 它不是一个独立的函数,它是PizzaController 实例上的一个方法

标签: javascript xml xmlhttprequest referenceerror


【解决方案1】:

dynamicSelectPizzaController 实例的属性,而不是当前范围内的变量。

使用箭头函数捕获PizzaController 的当前实例,然后使用this 访问其属性。

    xhttp.onreadystatechange = () => {
      if (this.readyState == 4 && this.status == 200) {
        this.dynamicSelect(xhttp.responseXML);
      }
    };     

【讨论】:

  • 我添加了你的代码,这就是我调用该函数的方式,我在浏览器上没有响应 window.onload = function () { document.getElementById("add").onclick = PizzaController.loadData; };
  • @CautionPackage — 您已将loadDataPizzaController 断开连接,因此this 丢失。见stackoverflow.com/questions/20279484/…
  • document.getElementById("add").onclick = () => PizzaController.loadData() 我试图找到解决方案,但它没有说明如何使用类调用它
  • 回顾代码……不要使用类。你没有做任何对使用类有意义的事情。如果你真的想使用类,那就学习如何使用new
  • 我有三层后端,所以我必须弄清楚一些事情。无论如何感谢您的回复
猜你喜欢
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多