jquery autocomplete json and clickable link through

后端 未结 2 1571
野的像风
野的像风 2021-02-11 07:03

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 :)

I have this code:



        
相关标签:
2条回答
  • 2021-02-11 07:35

    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" />
    
    0 讨论(0)
  • 2021-02-11 07:44

    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):
    https://jsfiddle.net/gbdarren/k2q5rfdh/5/

    0 讨论(0)
提交回复
热议问题