2012-05-03 94 views
-1

我试图实现输入字段,该输入字段在键入时显示建议。我已经找到了jquery自动完成功能,但是我正在努力将XML作为来自php的数据源。我的PHP文件创建一个这样的输出。使用php输出xml作为数据源的自动完成

XML:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<locations> 
    <location> 
     <number>600</number> 
     <name>Location Name 600</name> 
    </location> 

    <location> 
     <number>698</number> 
     <name>Location Name 698</name> 
    </location> 

    <location> 
     <number>1110</number> 
     <name>Location Name 1110</name> 
    </location> 
</locations> 

我已经张贴罗里McCrossan链接尝试过。

我的HTML现在看起来是这样的:

<!DOCTYPE HTML> 
<head> 
    <title>Autocomplete</title> 
    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> 
    <script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script> 
    <script type="text/javascript"> 
     $(function() { 
     function log(message) { 
      $("<div/>").text(message).prependTo("#output"); 
      $("#output").scrollTop(0); 
     } 

     $.ajax({ 
      url: "api.php", 
      dataType: "xml", 
      success: function(xmlResponse) { 
       var data = $("location", xmlResponse).map(function() { 
        return { 
         name: $("name", this).text(), 
         number: $("number", this).text() 
        }; 
       }).get(); 

       $("#locations").autocomplete({ 
        source: data, 
        minLength: 0, 
        select: function(event, ui) { 
         log(ui.item ? 
          "Selected: " + ui.item.name + ", number: " + ui.item.number : 
          "Nothing selected, input was " + this.value); 
        } 
       }); 
      } 
     }); 
    }); 
    </script> 
</head> 

<body style="background-color: black; color: white;"> 

<input id="locations" /> 

<div class="ui-widget" style="margin-top:2em; font-family:Arial"> 
    Result: 
    <div id="output" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div> 
</div> 

</body> 
</html> 

当我写的东西到输入字段,然后清除它,它让我看到3华里的下方的输入字段(这是我的位置量,根据XML),但没有文字显示在他们旁边。出了什么问题?

回答

0

好了,找到了解决办法为自己(决定创建JSON输出)。 Rory McCrossan的例子很好,但从我所看到的,它只是加载了一次xml,然后在xml中搜索。我想要的是预先过滤的输出,所以它不会传输太多的数据。

$(function() { 
     $("#locations").autocomplete({ 
      source: function(request, response) { 
       $.ajax({ 
        url: "api.php", 
        dataType: "jsonp", 
        data: { 
         location: request.term 
        }, 
        success: function(data) { 
         response($.map(data.locations, function(item) { 
          return { 
           label: item.name, 
           value: item.nummer 
          } 
         })); 
        } 
       }); 
      }, 
      minLength: 0, 
      select: function(event, ui) { 
       $("<div/>").text(ui.item.label + " " + ui.item.value).prependTo("#output"); 
      } 
     }) 
    }) 
1

要使用XML自动完成,在这里看到的例子:http://jqueryui.com/demos/autocomplete/xml.html

+0

这也适用于url:“api.php”而不是xml文件吗? – Ahatius

+0

是的,只要您包含'dataType:“xml”'设置来将预期格式显式设置为XML。 –

+0

自动填充方法存在一些问题,请参阅打开文章。 – Ahatius

相关问题