Fixed - AJAX and datalists

问题描述:

我试图使用XML从网站获取城市列表,然后通过并将每个城市添加到数据列表中,以便在我输入时会过滤城市在列表中。城市名单的Fixed - AJAX and datalists

例如:

Aleppo 
Alexandria 
Alger 
Almaty 
Ankara 
Anshan 
Baghdad 
Baku 
Bandung 
Bangalore 
Bangkok 
Barcelona 

* [每一个城市的名字是一个新行]

当前HTML:

<div id="namearea"> 
     <h2>City Name:</h2> 

     <div> 
      <input id="citiesinput" list="cities"> 
      <datalist id="cities"></datalist> 

      <button id="search"> 
       Search 
      </button> 

      <span class="loading" id="loadingnames"> 
       Loading... 
      </span> 
     </div> 
    </div> 

当前JS代码:

window.onload = function() { 
    var request = new XMLHttpRequest(); 
    request.onload = processCities; 
    request.open("GET", "url", true); 
    request.send(); 
}; 

检查页面h Firebug显示没有任何东西被添加到数据列表中,所以我想知道我做错了什么。我也尝试使用.responseText而不是.responeXML,但它没有任何区别。谁能帮我?编辑] 已取得进展。 我改变了processCities()函数:

function processCities() { 
    var response = this.responseText; 
    var city = response.split("\n"); 
    var options = ""; 

    for(var i = 0; i < response.length; i++) { 
     options += "<option value='"+city[i]+"'>\n"; 
    } 
    document.getElementById("cities").innerHTML = options; 
} 

此代码似乎工作。

感谢您的帮助。

+2

'response'将是一个XML DOM。您需要提供一个响应看起来对我们有帮助的例子。你所展示的不是XML。 –

以下是提出请求的示例。如果你真的在获取XML,那么你必须解析它。如果你能得到json,那会更好。

var request = new XMLHttpRequest(); 
 
request.open('GET', '/my/url', true); 
 

 
request.onload = function() { 
 
    if (request.status >= 200 && request.status < 400) { 
 
    // Success! 
 
    var data = JSON.parse(request.responseText); 
 
    } else { 
 
    // We reached our target server, but it returned an error 
 

 
    } 
 
}; 
 

 
request.onerror = function() { 
 
    // There was a connection error of some sort 
 
}; 
 

 
request.send();

+0

如果你将'response'设置为'responseText',循环它将返回响应中的每个字符... –

+0

好,赶上,我刚刚删除了那部分。我认为获得好的请求功能将是一个好的开始。 –

+0

我设法弄明白了一点,但这将有助于后期的任务,并帮助我弄清楚,所以谢谢你的帮助 – Sherpa