jquery autocomplete json and clickable link through

我的梦境 提交于 2019-12-03 09:00:13

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

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

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

The HTML on the page looks like so:

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

The real issue for me is getting the JSON data from the response into the autocomplete results

Just looking at your code, it looks like the autocomplete should be populating correctly. Are you sure the data is coming back? If you keep having problems, try using a local data source and see if the problems persist.

if any of these are clicked it directs the page to data.url.

You can accomplish this by defining an event handler for the select event:

$("input").autocomplete({
    /* Snip */
    select: function(event, ui) {
        window.location = ui.item.url;
    }
});

ui.item refers to the item that was selected in the dropdown.

Here's an example of this working (with a local data source): http://jsfiddle.net/andrewwhitaker/KBpXh/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!