JQuery UI自动完成语法

djs*_*s22 5 jquery jquery-ui jquery-ui-autocomplete

有人可以帮我理解下面的代码吗?我在这里找到.

它利用了远程源的JQuery UI Autocomplete.我尽可能地评论了代码,然后是一个更精确的问题.

    $( "#city" ).autocomplete({
        source: function( request, response )  {
//request is an objet which contains the user input so far
// response is a callback expecting an argument with the values to autocomplete with
            $.ajax({
                url: "http://ws.geonames.org/searchJSON", //where is script located 
                dataType: "jsonp", //type of data we send the script
                data: { //what data do we send the script 
                    featureClass: "P",
                    style: "full",
                    maxRows: 12,
                    name_startsWith: request.term
                },
                success: function( data ) { //CONFUSED!
                    response( 
                        $.map( 
                        data.geonames, function( item ) { 
                                            return {
                                                    label: item.name+(item.adminName1 ? ","+item.adminName1:"")+","+item.countryName,   
        value: item.name
                                            }
                                        }
                        )
                    );
                  }
            });
        }
    });
Run Code Online (Sandbox Code Playgroud)

如您所见,我不理解成功函数和响应回调的使用.

我知道success function literal是一个AJAX选项,在AJAX查询返回时调用.在这种情况下,它似乎封装了对响应回调的调用?哪个定义在哪里?我认为根据回调的定义,它应该自己调用?

谢谢!

And*_*ker 6

response文档定义的对象("概述"页面):

一个响应回调,它要求一个参数包含要向用户建议的数据.应根据提供的术语过滤此数据,并且可以采用上述任何简单本地数据格式(String-Array或具有标签/值/两者属性的Object-Array).在提供自定义源回调以处理请求期间的错误时,这很重要.即使遇到错误,也必须始终调用响应回调.这可确保窗口小部件始终具有正确的状态.

所以,'response'参数实际上是一个回调函数,必须在自动完成项的ajax检索成功时调用它.

由于您的数据将通过AJAX返回,因此您的代码必须手动更新小部件.jQueryUI提供了一个参数作为函数,以便您的代码可以通过调用该函数来执行该更新.

您可以response在用于该source选项的函数声明中看到定义的对象:

source: function( request, response )
Run Code Online (Sandbox Code Playgroud)

您甚至可以将AJAX调用从等式中取出并执行以下操作:

source: function(request, response) {
    response([{label:'foo', value: 'foo'},{label:'bar', value:'bar'}]);
}
Run Code Online (Sandbox Code Playgroud)

将立即response使用窗口小部件的标签/值对数组调用回调.