使用AJAX创建数据列表

时间:2016-05-13 01:52:40

标签: javascript jquery ajax datalist

我正在尝试使用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的新手。

请求页面的网页布局:

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

1 个答案:

答案 0 :(得分:0)

您在函数调用中缺少方括号()

(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应该是什么。