What are the “response” and “request” arguments in jQuery UI Autocomplete's “source” callback?

后端 未结 3 2007
一向
一向 2021-02-03 12:19

I\'m looking at the autocomplete tutorial, and I have a few questions: http://jqueryui.com/demos/autocomplete/#option-disabled

$( \"#tags\" )
            // don\         


        
3条回答
  •  有刺的猬
    2021-02-03 12:30

    No, request or response are not reserved keywords – if they were, you couldn't use them as function parameter names..

    What's going on here is pretty simple, and if you ever do anything in Node you'll see the pattern. It's async JavaScript.

    You're passing an anonymous function to source. This function is called whenever autocomplete needs to query the datasource (in other words, the user typed something).

    The function's parameters are request and response. request is simply the information autocomplete is requesting; request.term is the query (what the user typed). It's up to you how to implement the search – maybe you have a local variable with possibilities or you might make an AJAX call to the server.

    Now the important part: if you're making an AJAX call, you can't simply return a value from source() because the function will return long before the AJAX call completes. That's why there's a response parameter.

    response is a function reference passed to your source() function that you call whenever you have the answer to the request. Through the magic of closures, you can call this function from inside an AJAX callback.

    response (which could less confusingly be named callback) expects an array of strings or of objects with label and value properties. It will show those results in the autocomplete dropdown.

    Putting it all together:

    $('selector').autocomplete({
        ...
        source: function(request, response) {
            // calculate results for a query.
            response([{ label: 'Example', value: 'ex'  }]);
        }
    });
    

提交回复
热议问题