jqueryui自动完成和txt文件

时间:2015-09-02 17:51:47

标签: jquery file text autocomplete

我有这些.txt文件:

one;uno
two;dos
three;tres
four;cuatro

这个HTML脚本:

  <script>
  $(function() {
    var availableTags = [
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });
  </script>

如何在

的括号中编写.txt第一列的项目
var availableTags = [ ];

更新:这似乎不是调用.txt文件的正确方法:

<script>

$.get('dicc.txt', function(data) {

var i;
var pos = 0;
var availableTags = [];

x = x.split(/[\;,\n]+/);

for (i = 0; i < x.length; i = i + 2)
  availableTags[pos++] = x[i];

console.log(availableTags);

$(function() {
  $("#tags").autocomplete({
    source: availableTags
  });
});

}, 'text');

</script>

1 个答案:

答案 0 :(得分:1)

'text'请求中使用$.get()数据类型。否则jQuery会猜测返回的内容。

尝试以下方法:

$.get('source_file.txt', function(data) {
  var i;
  var pos = 0;
  var availableTags = [];

  data = data.split(/[\;,\n]+/); //split text using regex (separators: ';' and '\n')

  for(i = 0; i < data.length; i = i + 2)
     availableTags[pos++] = x[i];

}, 'text');

因为我无法访问任何文本文件,所以我使用字符串做了一个jQueryUI自动完成的例子:

var x = "one;uno\ntwo;dos\nthree;tres\nfour;cuatro";

var i;
var pos = 0;
var availableTags = [];

x = x.split(/[\;,\n]+/);

for (i = 0; i < x.length; i = i + 2)
  availableTags[pos++] = x[i];

console.log(availableTags);

$(function() {
  $("#tags").autocomplete({
    source: availableTags
  });
});
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="ui-widget">
  <label for="tags">Tags:</label>
  <input id="tags">
</div>

这是 DEMO 。观察值在控制台选项卡中availableTags中的存储方式。

请记住,$.get只是$.ajax的便利包装器。数据类型列在$.ajax() docs

是的,欢迎来到社区! ;)