【发布时间】:2014-12-07 19:56:18
【问题描述】:
我有一个带有输入字段的 html 页面。每次在此字段中键入内容时,都会使用 jQuery 调用 php 脚本。
这个 php 脚本根据输入字段返回一个带有特定查询结果的 JSON。
这工作正常,我将输出记录到console。
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
var r = jQuery(function($) {
$('#name').keyup(function() {
var input = $('#name').val();
var response = $.getJSON('get_names.php', {input: input});
response.done(function (names) {
console.log(names);
});
});
});
</script>
</head>
<body>
<div><input id="name"></div>
</body>
</html>
现在的问题是,我需要将其与 twitter 引导程序 - first example in typeahead.js 合并,而不是记录到 console,以便每次使用的 json(以下代码中的 states)由带有字段内容的php脚本。
$(document).ready(function() {
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push({ value: str });
}
});
cb(matches);
};
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
$('#the-basics .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
source: substringMatcher(states)
});
});
我一直试图用这个来捕捉价值,但没有任何改变:
jQuery(function($) {
$('#name').keyup(function() {
var input = $('#name').val();
names = $.getJSON('get_names.php', {input: input});
});
});
那么:我怎样才能在每次发生keyup 事件时更新 JSON,方法是调用 php 脚本并使用迄今为止编写的输入?
【问题讨论】:
-
@guest271314 谢谢。但是,在此示例中,我没有看到您正在调用提供 JSON 返回的脚本。这个 JSON 似乎是静态的。
标签: jquery json twitter-bootstrap typeahead.js bootstrap-typeahead