帮助获取传递到 Jquery 自动完成插件的正确信息以获得可点击的结果
所以我对下面的代码有问题。我有一个格式化的数组:
{label:movie, value:location}
以下代码将仅在搜索框中显示标签,单击时使用该信息来创建 URL。我需要它传递数组中的值字段而不是标签。我尝试将 suggest.push(val.label) 更改为 suggest.push(val.value),此时单击网址有效,但网址显示在搜索框中而不是标签中。我对 Jquery 和 Json 很陌生,所以我真的很盲目。
$(function(){
//attach autocomplete
$("#to").autocomplete({
minLength: 2,
//define callback to format results
source: function(req, add){
//pass request to server
$.getJSON("/movie.php?callback=?", req, function(data) {
//create array for response objects
var suggestions = [];
//process response
$.each(data, function(i, val){
suggestions.push(val.label);
});
//pass array to callback
add(suggestions);
});
},
focus: function (event, ui) {
$(event.target).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
},
});
});
So I have a problem with the following code. I have an array that is formatted:
{label:movie, value:location}
The following code will only show the label in the search box and when clicked uses that information to make the url. I need it to pass the value field from the array instead of the label. I've tried changing suggestions.push(val.label) to suggestions.push(val.value) at which point the clicking url works but the url shows in the searchbox instead of the label. I'm new to Jquery and Json so am really flying blind.
$(function(){
//attach autocomplete
$("#to").autocomplete({
minLength: 2,
//define callback to format results
source: function(req, add){
//pass request to server
$.getJSON("/movie.php?callback=?", req, function(data) {
//create array for response objects
var suggestions = [];
//process response
$.each(data, function(i, val){
suggestions.push(val.label);
});
//pass array to callback
add(suggestions);
});
},
focus: function (event, ui) {
$(event.target).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
},
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你很接近。您不需要在
success
回调中进行后处理:自动完成小部件可以采用对象数组,只要这些对象具有
标签
和/或value
属性。由于您已在 AJAX 调用的结果中提供了这两者,因此您应该通过直接调用
add
函数作为 AJAX 回调的 success 方法来获得所需的行为。You are close. You don't need the post-processing that you're doing in the
success
callback:The autocomplete widget can take an array of objects, as long as those objects have a
label
and/orvalue
property.Since you've supplied both in the result of your AJAX call, you should get the behavior you want by calling the
add
function directly as the success method of your AJAX callback.