【问题标题】:jQuery UI autocomplete with pre-transformed json url带有预先转换的 json url 的 jQuery UI 自动完成
【发布时间】:2017-01-24 05:10:30
【问题描述】:

好的,所以我知道 jQueryUI 期望对象以键/值形式使用键的“值”和“标签”,所以我已经将我的数据转换为这种 json 格式。现在我只是不确定如何最简单地获取我的 json url。关于这个问题的所有其他文章都表明需要提取数据并对其进行转换,这不是我的情况。

我的 json 文件位于 getuser.php?name=brian

[
   {"label":"Brian Aa","value":"7e36e"},
   {"label":"Brian Ba","value":"3e497"},
   {"label":"Brian Bc","value":"c3263"},
   {"label":"Brian Cc","value":"5be94"}
]

我的自动完成 JS:

$("#test").autocomplete({
  source: function(request, response) {
    "sample.com/getusers.php?name="+$("#test").val(), request, response;
  },
  minLength:2
});

HTML

<div>
  <label for="tags">Requested By: </label>
  <input id="test">
</div>

现在我在输入时什么都没有,假设我必须设置 ajax,但我认为当 JSON 已经格式化但似乎找不到它时,我看到了一个非常简单的解决方案示例。

【问题讨论】:

  • 您需要“获取 JSON URL”是什么意思?
  • 我有一个页面 (getuser.php),如果您在 url 中提供参数 (?name=brian),它将提供 json 格式的数据,例如我的问题中显示的 json 转储
  • 也许我睡眠不足,但我还是不明白你的意思。您是说要使用 json 数组作为对象的“源”属性吗?第一个示例here 使用数组显示它们..
  • 来自documentation...."带有标签和值属性的对象数组:[ { label: "Choice1", value: "value1" }, ... ]" - 这个是我想要使用的 json 格式。

标签: javascript php jquery json jquery-ui


【解决方案1】:

源函数不对,需要从服务器获取数据并使用response作为调用,见Autocomplete API

  source: function(request, response) {
     var url = "sample.com/getusers.php?name="+$("#test").val();
     $.get(url).done(function(data){
       response(data);
     }).fail(function(error){
        //dosomething here
     });
  }

【讨论】:

  • 这不是真的。该页面上的第一个示例使用数组而不是 AJAX 调用。
【解决方案2】:

这是一个ajax调用的问题,我只是认为有一个更简单的方法。

$( function() {
  $( "#test" ).autocomplete({
    source: function( request, response ) {
      $.ajax( {
        url: "sample/getusers.php?name="+$("#test").val(),
        dataType: "json",
        data: {
          term: request.term
        },
        success: function( data ) {
          response( data );
        }
      } );
    },
    minLength: 2,
    select: function( event, ui ) {
    }
  } );
} );

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2018-02-16
    • 2017-09-19
    • 2021-05-27
    相关资源
    最近更新 更多