Javascript 这个javascript响应函数有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5182567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does this javascript response function do?
提问by Dismissile
I saw this code in another SO post: jQuery UI Autocomplete with ASP MVC
我在另一篇 SO 帖子中看到了这段代码:jQuery UI Autocomplete with ASP MVC
$("#CustomerID").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/customer/search",
dataType: "json",
data: {
term: request.term
},
error: function(xhr, textStatus, errorThrown) {
alert('Error: ' + xhr.responseText);
},
success: function(data) {
response($.map(data, function(c) {
return {
label: c.Company,
value: c.ID
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
alert('Select');
}
});
I understand everything except the success function. I know that map is taking an array and mapping each value to a new object that has a label and value property and returning the new array, but I am not sure what response() does.
我理解除了成功功能之外的一切。我知道 map 正在获取一个数组并将每个值映射到一个具有 label 和 value 属性的新对象并返回新数组,但我不确定 response() 的作用。
回答by David Waters
This object called response is a call back function passed to the function labeled source by the autocomplete method.
这个名为 response 的对象是一个回调函数,通过 autocomplete 方法传递给标记为 source 的函数。
The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".
A responsecallback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties). It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
第三个变体回调提供了最大的灵活性,可用于将任何数据源连接到自动完成。回调有两个参数:
一个请求对象,有一个名为“term”的属性,它指的是当前文本输入中的值。例如,当用户在城市字段中输入“new yo”时,自动完成术语将等于“new yo”。
一个响应回调,它需要一个参数来包含向用户建议的数据。此数据应根据提供的术语进行过滤,并且可以采用上述用于简单本地数据的任何格式(带有标签/值/两个属性的字符串数组或对象数组)。在提供自定义源回调以处理请求期间的错误时,这一点很重要。即使遇到错误,您也必须始终调用响应回调。这确保小部件始终具有正确的状态。
回答by Nikhil
It appears to be a custom function that the original coder's code has. To the best of my knowledge this is not an inherent jQuery function.
它似乎是原始编码器代码具有的自定义函数。据我所知,这不是一个固有的 jQuery 函数。