使用AJAX创建数据列表

Using AJAX to create a datalist

本文关键字:列表 数据 创建 AJAX 使用      更新时间:2023-09-26

我正试图使用AJAX添加到数据列表中。我请求的网页上只有每个城市的名字。我基本上有:

(function() {
"use strict";
    window.onload = function() {
        fetch("cities");
    };
    function fetch(mode) {
        var request = new XMLHttpRequest();
        request.onload = getCities();
        request.open("GET", "https://weather.com/weather/mode=" + mode, true);
        request.send();
    }
    function getCities() {
        //loop while there's data/string to grab {
            var city = document.createElement("option"); 
            city.innerHTML = this.responseText; //set the option as the name of the city from the request
            document.getElementById("cities").appendChild(city);
        }
    }
}) ();

该网页只是我在服务器上使用的网页的填充物,但我试图为每个字符串创建一个新的选项标签,并将其附加到我的html中的数据列表中,但我在捕捉任何内容时遇到了问题。出于某种原因,我只是得到了一个未定义的错误。对不起,我是javascript和AJAX的新手。

请求页面的网页布局:

阿比让阿克拉阿达纳亚的斯亚贝巴艾哈迈达巴德阿勒颇亚历山大Alger阿拉木图安卡拉鞍山巴格达巴库万隆班加罗尔曼谷

函数调用中缺少括号()

(function() {
    "use strict";
    window.onload = function() {
        fetch("cities");
    };
    function fetch(mode) {
        var request = new XMLHttpRequest();
        request.onload = getCities();      // <- brackets missing here
        request.open("GET", "https://weather.com/weather/mode=" + mode, true);
        request.send();                    // <- and here
    }
    function getCities() {
        var city = document.createElement("option");
        document.getElementById("cities").innerHTML = this.responseText;
    }
}) ();

我也不清楚getCities函数应该如何工作。您正在创建一个选项集,但没有将其添加到DOM中。我也不确定this.responseText应该是什么。