Autocomplete jQuery with Wordpress

后端 未结 1 593
[愿得一人]
[愿得一人] 2021-01-28 16:13

I want to retrive data from a json file using Jquery autocomplete and ajax call in Wordpress.

This is my code:

HTLM

相关标签:
1条回答
  • 2021-01-28 17:00

    Think for a moment about what you are doing here how it is supposed to work:

    $(function(){
        $( "#comuni" ).autocomplete({
           source: function( request, response ) {
                $.ajax({
                        type: 'POST',
                        url: ajaxUrl,
                        data: {
                        action: "mon_action"
                         },
                        success: function(data) {
                        response( $.map(data, function(item) {
                            return item.nomeComune;
                         }));
                     }
                   });
                },
           minLength: 3,
    }
    

    According to jQuery documentation passing anonymous function to source option of autocomplete gives you possibility to filter suggestions based on current value of given input (stored in request.term property) by doing your custom request.
    It seems though, that you just want to fetch your json once and use it as source.
    In order to do so you need to move your invocation of jQuery.autocomplete function to success callback of "mon_action" backend API endpoint.

     $.ajax({
             type: 'POST',
             url: ajaxUrl,
             data: {
               action: "mon_action"
              },
              success: function(data) {
                  $( "#comuni" ).autocomplete({
                   // TODO: parse data properly
                   source: data
                 })
             }
           });
    

    Luckily there is another error in your code, luckily, because otherwise autocompletion would work and you wouldn't notice, that there are hundreds of unnecessary requests.
    You don't want to map data directly (which is JSON object, so you cannot map it), you want to map "comuni" property of your data, which is an array.

    $.map(data.comuni, function(item) {
         return item.nomeComune;
        })
    
    0 讨论(0)
提交回复
热议问题