jquery自动完成json和可点击链接

Mar*_*tin 2 jquery json jquery-ui autocomplete jquery-ui-autocomplete

我已经在这一段时间了,我的进展非常缓慢,主要是因为我的jquery技能需要改进,我正在尝试:)

我有这个代码:

jQuery(function() {
  jQuery("input#search").autocomplete({
    minLength: 2,
    source: function(request, response) { 
      jQuery.post("index.php?option=com_eat&view=search&format=raw", { 
        "'.$token.'": "1",
        search_string: request.term
      }, function(data) { 
        response( jQuery.map( data, function( item ) {
          return {
            value: item.name,
            url: item.url
          }
        }));
      }, "json"); 
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

帖子的回报是以下形式的json:

data.url = some_url;
data.name = some_name;
Run Code Online (Sandbox Code Playgroud)

我想让json data.name填充自动完成功能,如果点击其中任何一个,它会将页面指向data.url.

对我来说真正的问题是将响应中的JSON数据转换为自动完成结果.在网上没有太多适合我情况的例子,我找不到.

谢谢你的帮助.

Mar*_*tin 12

我设法解决了我的问题,见下文(注意:$ token是一个php变量).这允许我发送(特别是发布)多于1个变量到返回JSON响应的php脚本.在我的情况下,这是必要的,因为我使用令牌来防止未经授权访问搜索功能.

jQuery(function() {
  jQuery("#search").autocomplete({
    source: function(request, response) {
      jQuery.ajax({
        url: "index.php?option=com_eat&view=search&format=raw",
        type: "post",
        dataType: "json",
        data: {
          search_string: request.term,            
          "'.$token.'": "1"
        },
        success: function(data) {
          response(jQuery.map(data, function(item) {
            return {
                url: item.url,
                value: item.name
            }
          }))
        }
      })
    },
    select: function( event, ui ) {
      window.location.href = ui.item.url;
    },
    minLength: 2
  });
});
Run Code Online (Sandbox Code Playgroud)

index.php返回的JSON?option = com_eat&view = search&format = raw看起来像:

[{"url":"url1", "name":"name1"}, {"url":"url2", "name":"name2"}, ...]
Run Code Online (Sandbox Code Playgroud)

页面上的HTML看起来像这样:

<input type="text" size="30" id="search" />
Run Code Online (Sandbox Code Playgroud)