我想将一组数据从php传递给typeahead,但它不起作用,我不知道我做错了什么。我已经检查了其他问题,但无法获得解决方案。我尝试在控制台上显示响应,它显示字符串数组但在typeahead字段中没有任何内容
PHP
$resp = array();
$states = $this->cj_model->list_all_states();
foreach($states as $row){
$resp[] = $row['name'];
}
echo json_encode($resp);
JS
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)) {
matches.push(str);
}
});
cb(matches);
};
};
AJAX
function get_states()
{
$.ajax({
url: 'country/get_states/',
dataType: 'json',
type: 'get',
async: true,
success: function(response){
return (response);
},
error: function(jqxhr, textStatus, error){
console.log(error);
}
});
}
var states = get_states();
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: substringMatcher(states)
});
答案 0 :(得分:1)
问题是你试图在ajax成功函数上返回一些东西。 在那种情况下,因为ajax执行异步请求是不可能的。 写这样的代码。
john@@doe.com