Javascript中的XMLHttpRequest.onload构造函数?

时间:2018-01-20 14:45:44

标签: javascript ajax constructor

制作新的XMLHttpRequest时,如此

let http = new XMLHttpRequest();

有一个名为onload的方法(属性?)。我的问题是,为什么我们可以为它分配一个函数?像这样

http.onload = function(){};

如果onload是XMLHttpRequest中的一个属性,当我们为它赋予一个新值时,它的值会改变,对吧?

XMLHttpRequest.onload构造函数是什么样的? 我对此感到很困惑。

2 个答案:

答案 0 :(得分:0)

当我们第一次开始编写HTML事件处理程序时,我们会编写

<button onclick="alert('Hey you')"> Say Hi</button>

当您将HTML转换为DOM时,您将获得对对象的引用,您还可以通过将属性设置为函数来设置该事件处理程序。当用户单击按钮时,浏览器将为您调用该功能。 这是一个使用属性作为回调的穷人事件系统

这是设置事件处理程序的两种方法:

  • XML属性
  • 通过设置属性
  • 进行DOM元素引用

过了一会儿,他们意识到可能需要设置多个侦听器(覆盖属性会覆盖以前的侦听器)。我们创建了hacks以允许通过创建调用其他函数的函数来设置多个处理程序,并且需要一个真实的事件系统。 DOM元素变为EventTarget,您现在可以使用更常见的事件接口。

buttonEl.addEventListener('click', () => console.log('clicked'));
buttonEl.addEventListener('click', () => console.log('second handler'));

所以我们有三种不同的方式来设置事件。 XmlHttpRequest也会实现自己的XMLHttpRequestEventTarget事件目标,因此您可以设置&#34;事件&#34;通过回调属性和addEventListener两种方式。

在你的问题中,你说:&#34; XMLHttpRequest.onload构造函数是什么样的?&#34;您可能意味着我们如何覆盖onload属性,因为属性没有构造函数,其值具有构造函数,但我们通常使用文字赋值。它最初未设置(undefined),如果它从未设置,则不会被调用。

答案 1 :(得分:0)

它在程序中使用了 XMLHttpRequest(); 一切都在每个浏览器的 ChromeDev 上运行。但是,当我尝试在其他浏览器中运行该页面时,此方法被阻止。

[在此处输入图片描述][1] [1]:https://i.stack.imgur.com/mfE0k.png

在 MDN 文档中写道,目前所有浏览器都支持该方法。 有谁知道为什么我不能在其他浏览器中运行我的脚本?

function loadDocumentCsv() {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function () {
    const request = this.responseText.toString();
    const allRecords = downloadElement("#allRecords");
    const isofixTrue = downloadElement("#isofixTrue");
    const brandSort = downloadElement("#brandSort");
    const sortMileageAndIsofixFalse = downloadElement("#sortMileageAndIsofixFalse");

    allRecords.innerHTML = "";
    isofixTrue.innerHTML = "";
    brandSort.innerHTML = "";
    sortMileageAndIsofixFalse.innerHTML = '';

    const arrayData = request.replace(/\n/g, ",").split(",");

    const newArray = arrayData.map((element, index) => {
      element.trim();
      if (index > 4) {
        if (index % 5 === 2) {
          const cutLetters = element.replace(/[^0-9]+/, "");
          element = Number(cutLetters.substring(cutLetters.length - 4, cutLetters.length));
          if (element == 0) element = 2007;
        } else if (index % 5 === 3) {
          element = Number(element.replace(/[^0-9]+/, ""));
        } else if (index % 5 === 4) {
          element = element.trim() === "TRUE";
        }
      }
      return element;
    });

    const arrayOfArrays = [];
    while (newArray.length) {
      const addArrayToArrays = newArray.splice(0, 5);
      arrayOfArrays.push(addArrayToArrays);
    }

    //header table
    const header = arrayOfArrays.splice(0, 1);
    const firstRow = (table) =>
      header.forEach((el) => {
        const item = templateHtml(el, "font-weight-bold");
        table.appendChild(item);
    });
    
    //ALL CARS
    firstRow(allRecords);
        arrayOfArrays.forEach((element, index) => {
          const item = templateHtml(element);
          allRecords.appendChild(item);

          const item2 = templateHtml(element);
          element[4] === true || index === 0 ? isofixTrue.appendChild(item2) : "";
        });

    //isofix == TRUE
    firstRow(isofixTrue);

    //sort Brand
    firstRow(brandSort);
    arrayOfArrays.sort(sortedBrand);
    arrayOfArrays.forEach((element) => {
      const item = templateHtml(element, "font-weight-normal");
      brandSort.appendChild(item);
    });

    // sortMileageAndIsofixFalse
    firstRow(sortMileageAndIsofixFalse);
    arrayOfArrays.sort((prev, next) => prev[3]- next[3]);
    arrayOfArrays.forEach((element) => {
      const item = templateHtml(element, "font-weight-normal");
      element[4] === false ? sortMileageAndIsofixFalse.appendChild(item) : "";
    });
  };
  xhttp.open("GET", "Cars.csv");
  xhttp.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
        integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
            integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
            crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/solid.css">
    <link rel="stylesheet" href="./css/style.css">
</head>
<body id="body">
    <section class="container loadClick mb-5">
                <button type="button" onclick="loadDocumentCsv()" class="btn loadDocument font-weight-bold">Wyświetl wszystkie tabele</button>
    </section>

    <section class="container">
        <h2>1. Wszystkie samochody</h2>
        <div id="allRecords"></div>
    </section>

    <section class="container mt-5">
        <h2>2. Samochody gdzie Isofix === TRUE</h2>
        <div id="isofixTrue"></div>
    </section>

    <section class="container mt-5">
        <h2>3. Posortowane samochody wg Marki</h2>
        <div id="brandSort"></div>
    </section>

    <section class="container mt-5">
        <h2>4. Samochody gdzie Isofix === FALSE, posortowane wg przebiegu od najmniejszego do największego</h2>
        <div id="sortMileageAndIsofixFalse"></div>
    </section>
    
    <div id="fixed">
        <a href="#body"><i class="uis uis-arrow-circle-up"></i></a>
    </div>
    
    <script src="./index.js"></script>
</body>
</html>

CSV 文件如下所示: 品牌、型号、生产年份、里程、Isofix 阿尔法罗密欧,156,1998,600 000,TRUE 克莱斯勒,航海者,2007,342 121,FALSE 智能,敞篷车,2005,422122,TRUE 菲亚特,500,2001 未知,121333,FALSE 克莱斯勒,航海者,2005,421 325,FALSE Smart,Liftback,2015,534531,TRUE