在JSON对象上迭代

大家好, 我通常是Perl程序员,我在JavaScript中有一些背景,并试图创建Googleish Selector Div. 请忍受我,请原谅长期的介绍... 这是细节: 我们的网站按位置过滤内容. 我使用邮政编码查找半径. 因此,如果用户想从他们不知道邮政编码的位置查看内容,我已经设置了这个整洁的小输入字段,使您可以键入zipcode或city名称. 一旦您开始键入城市名称,它就会为所有"启动"的城市查询一个数据库. 一切都很好,但是由于对我的CGI脚本的所有重复请求,我注意到延迟. (我正在使用onkeyup事件来触发AJAX请求.) 所以!! 我有这个Brite的想法可以在输入的第一个字母中查询一次数据库,让Perl脚本返回JSON对象并使用JavaScript进行进一步的过滤(在后续的键盘事件上) 仅提出一个AJAX请求,然后使用从该请求中返回的数据来进一步缩小结果. 如果用户回到输入字段为空的位置,则我将arbitary变量设置为"空",下一个字母进入新的Ajax请求将使用新的"第一个"字母进行. 所以我的问题... 我如何迭代返回的JSON对象? 到目前为止,这是我的代码:

选择 | 换行 | 行号
  1. // AJAX CODE //
  2. // !!!!!!!!!
  3.  
  4. var response = 'empty'; // my arbitrary var that decides weather to AJAX or not.
  5.  
  6.  
  7. // My AJAX request function...
  8. function makeRequest(url) {
  9.         var httpRequest;
  10.  
  11.         if (window.XMLHttpRequest) { // Mozilla, Safari, ...
  12.             httpRequest = new XMLHttpRequest();
  13.             if (httpRequest.overrideMimeType) {
  14.                 httpRequest.overrideMimeType('text/xml');
  15.                 // See note below about this line
  16.             }
  17.         }
  18.         else if (window.ActiveXObject) { // IE
  19.             try {
  20.                 httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
  21.                 }
  22.                 catch (e) {
  23.                            try {
  24.                                 httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  25.                                }
  26.                              catch (e) {}
  27.                           }
  28.                                        }
  29.  
  30.         if (!httpRequest) {
  31.             alert('Giving up :( Cannot create an XMLHTTP instance');
  32.             return false;
  33.         }
  34.         httpRequest.onreadystatechange = function() { response = httpRequest.responseText;
  35.  
  36. // Here I set the global var response to the JSON object
  37. // and call the function that updates the div on the page. "updateAjax()"
  38.                                                       updateAjax();
  39.                                                         };
  40.         httpRequest.open('GET', url, true);
  41.         httpRequest.send('');
  42.  
  43.     }
  44.  
  45. // THIS is the function that get's called each time a user types a letter...
  46.     function assembleRequest(b) {
  47. // First make hidden "result" div visible...(cross browser)
  48.     if(document.getElementById){
  49.             document.getElementById('result').style.visibility='visible';
  50.             }
  51.             else if(document.all && !document.getElementById){
  52.             document.all.result.style.visibility='visible';
  53.             }
  54. // Find out if they have cleared the input field...
  55.     if(b.value){
  56.         if(response == 'empty'){ // If so make new AJAX request...
  57.         makeRequest('ajax/cityAjax.cgi?city='+b.value);        
  58.         }
  59. // If not just filter through what we already have...
  60.         else{
  61.         updateAjax(b);
  62.         }
  63.     }
  64. // If they have cleared the field set flag to ensure new AJAX request on next letter entered.
  65.     else{
  66.     response = 'empty';
  67.     }
  68.     }
  69.  
  70.  
  71.  
  72. //  THIS is where the problem is... I need to iterate over the JSON object
  73. // and use regexe to see if the "city name" field matches...
  74.  
  75.     function updateAjax(b){
  76.  
  77.         var inputText = b.value;
  78.         var responseText = response;
  79.  
  80.         for(responseText){
  81.  
  82.        // WHAT TO DO HERE????  
  83.        // I WANT to generate a: "<option value="27603">Raleigh, NC</option>"
  84.        //  kinda thing for each element in the JSON object...
  85.         }
  86.  
  87.  
  88.  
  89.         document.getElementById("result").innerHTML = responseText;
  90.  
  91.  
  92.     }
  93.  
  94.  
  95.  
  96. // This function just updates the input field to the correct zip, for submitting the form...
  97.     function inputCity(e){
  98.  
  99.     var it = e.cities.options[e.cities.selectedIndex].value;
  100.  
  101.     if (it != ""){
  102.             if(document.getElementById){
  103.             document.getElementById('zipcode').value = it;
  104.             document.getElementById('result').style.visibility='hidden';
  105.             document.getElementById('result').blur();
  106.             }
  107.             else if(document.all && !document.getElementById){
  108.             document.searchZip.zipcode.value = it;
  109.             document.all.result.style.visibility='hidden';
  110.             document.all.result.blur();
  111.             }
  112.  
  113.     }
  114.     else{
  115.     alert('Error completing request');
  116.    }
  117. }
  118.  
  119. // END AJAX
  120. //
  121. //
  122.  

从我的perl脚本返回的JSON对象是这种格式: $ json = { 27603:罗利:NC, 25071:elkview:WV, 10001:纽约:纽约, ETC.... }; 我如何到达城市名称字段,看看它是否与用户输入的文本匹配??? 任何帮助将不胜感激!!! 在尝试使用JSON和REPONSONDS标志VAR之前,我的工作原理(尽管缓慢而不稳定). 谢谢!

# 回答1

那不是有效的JSON结构. 使用逗号分隔状态是最简单的. 这样,您可以轻松地循环浏览数组并找到部分匹配项. 确保将JSON结构粘贴到Firebug的控制台时起作用. 如果您发布了工作的JSON,我可以为您制定迭代代码.
# 回答2

好的,我想我应该问; "我将如何在JSON中创建一个关联数组?". 我需要知道城市名称,州和邮政编码,以创建选择选项. 例如 转动

选择 | 换行 | 行号
  1.  
  2. var json = { 27603 : [ "Raleigh", "NC"] , 25071 : [ "Elkview", "WV"] };
  3.  

在此中:

选择 | 换行 | 行号
  1. <option value="27603">Raleigh, NC</option>
  2. <option value="25071">Elkview, WV</option>
  3.  

然后,我可以学习如何迭代结构... :) 还是这样组装会更容易: var json = {" raleigh":[27603," nc"]," elkview":[25071," wv"]}; 我可以让perl脚本返回任何类型的格式,我选择了JSON而不是XML,因为我认为使用JavaScript操作会更容易. 实际上,我可以让它返回一个JavaScript数组,但是我需要三个阵列吗? 啊! 现在我很困惑...

# 回答3

好的,进行了一些重新检查,并更改了我的perl脚本,我认为我有一个正确的JSON对象. 这是输出 将字母的" X"传递给MakereQuest功能. (实际上是" cityajax.cgi?input = x"是准确的)

选择 | 换行 | 行号
  1. { "options" : [ { "value" : 45385, "label" : ["Xenia", "OH"]}, { "value" : 62899, "label" : ["Xenia", "IL"] } ] }
  2.  

这是否会创建带有邮政编码值和城市" lable"的值的选项? 我再次伸手去拿:

选择 | 换行 | 行号
  1. <option value="45385">Xenia, OH</option>
  2. <option value="62899">Xenia, IL</option>
  3. etc...
  4.  

在此之后,我将攻击Regexe,过滤零件.

标签: Javascript

添加新评论