jQuery自动完成JSON和可点击链接 [英] jquery autocomplete json and clickable link through

查看:57
本文介绍了jQuery自动完成JSON和可点击链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been at this for a while and I'm making very slow progress mostly because my jquery skills need improvement, I am trying though :)

我有此代码:

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"); 
    }
  });
});

帖子的返回值为json,格式为:

The return from the post is json in the form:

data.url = some_url;
data.name = some_name;

我想用json data.name填充自动完成功能,如果单击其中任何一个,它将页面定向到data.url.

I want to have the autocomplete populated by the json data.name and if any of these are clicked it directs the page to data.url.

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

The real issue for me is getting the JSON data from the response into the autocomplete results. There aren't too many examples of this on the web that suit my circumstances, well none that I can find.

感谢您的帮助.

推荐答案

我设法解决了我的问题,请参见下文(注意:$ token是一个php变量).这使我可以向返回JSON响应的php脚本发送(特别是发布)多个变量.就我而言,这是必要的,因为我使用令牌来防止未经授权访问搜索功能.

I managed to solve my problem, see below (NOTE: $token is a php variable). This allows me to send (specifically post) more than 1 variable to the php script that returns the JSON response. In my case this is necessary as I use a token to prevent unauthorised access to the search functionality.

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
  });
});

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

The returned JSON from index.php?option=com_eat&view=search&format=raw looks like:

[{"url":"url1", "name":"name1"}, {"url":"url2", "name":"name2"}, ...]

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

The HTML on the page looks like so:

<input type="text" size="30" id="search" />

这篇关于jQuery自动完成JSON和可点击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆