我已经尝试了几个小时,才能在“远程”路径中获取变量。该变量将更改,具体取决于另一个输入。这是代码:
school_value = $('#school').val();
$('#school').change(function () {
school_value = $(this).val();
$('#programme').typeahead('destroy'); // I have also tried with destroy - but it doesnt work.
});
$('#programme').typeahead({
remote: 'typeahead.php?programme&type=1&school_name=' + school_value,
cache: false,
limit: 10
});
在远程地址中未设置变量'school_type',因此不会调用。
您是否有任何使其工作的线索?我刚刚从Bootstrap 2.3切换到了3,然后注意到不推荐使用typeahead。上面的代码可在Bootstrap 2.3上运行,但是似乎在初始化脚本时,远程路径已锁定。
我已经找到解决方案!代码:
$('#programme').typeahead({
remote: {
url: 'typeahead.php?programme&type=1&school_name=',
replace: function () {
var q = 'typeahead.php?programme&type=1&school_name=';
if ($('#school').val()) {
q += encodeURIComponent($('#school').val());
}
return q;
}
},
cache: false,
limit: 10
});
基于此线程的答案:Bootstrap 3 typeahead.js - remote url attributes
请参见typeahead.js docs中的功能“替换”
我相信已被接受的答案已经过时。 remote
选项不再具有replace
。相反,您应该使用prepare
:
$('#programme').typeahead({
remote: {
url: 'typeahead.php?programme&type=1&school_name=',
prepare: function (query, settings) {
settings.url += encodeURIComponent($('#school').val());
return settings;
}
}
});
我遇到的一个问题是从另一个typeahead
对象中提取值。 Typeahead本质上会复制您的输入,包括所有类,因此您有两个几乎相同的对象,一个对象为tt-hint
类,另一个对象为tt-input
。我必须指定它是tt-input
选择器,否则我得到的值是一个空字符串。
$('.field-make').val(); // was "" even though the field had a value
$('.field-make.tt-input').val(); // gave the correct value
实际上,较新的Bloodhound js中对Mattias的回答进行了一些细化,这减少了重复和出错的机会:
$('#programme').typeahead({
remote: {
url: 'typeahead.php?programme&type=1&school_name=',
replace: function (url, query) {
if ($('#school').val()) {
url += encodeURIComponent($('#school').val());
}
return url;
}
},
cache: false,
limit: 10
});
@ Mattias,请注意,您可以通过提供可选的replace
参数来稍微清理url
方法。
$('#programme').typeahead({
remote: {
url: 'typeahead.php?programme&type=1&school_name=',
replace: function (url, query) {
// This 'if' statement is only necessary if there's a chance that the input might not exist.
if ($('#school').val()) {
url += encodeURIComponent(('#school').val());
}
return url;
}
},
cache: false,
limit: 10
});
我和你们所有人都在看相同的东西吗?
http://www.runningcoder.org/jquerytypeahead/
似乎再次改变了!如何做到这一点在文档中不是很明显,但是有示例代码。我直接从文档中的代码中提取了此信息。
文档中还有另一个例子,他们以另一种方式来做!我认为这是最简洁的方式。
// Set a function that return a request object to have "dynamic" conditions
dynamic: true,
source: {
tag: {
ajax: function (query) {
if (query === "hey") {
query = "hi"
}
return {
url: "http://www.gamer-hub.com/tag/list.json",
dataType: "jsonp",
path: data,
data: {
q: query
}
}
}
}
}
这是我的工作示例:
source: {
ajax: function() {
var filter = {
partnerId: @Model.PartnerId,
productTypeId: @Model.ProductTypeId,
unitType: $("[name=UnitType]").val(),
manufacturer: "",
columnName: "@nameof(SaleViewModel.Manufacturer)"
};
var queryString = $.param(filter);
return {
url: recentEntriesBaseUrl + "?" + queryString
}
}
},