gpt4 book ai didi

javascript - 无法使用 php 将 json 数据传递给 typeahead

转载 作者:太空宇宙 更新时间:2023-11-04 16:10:45 25 4
gpt4 key购买 nike

我想将一组数据从 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)
});

最佳答案

问题是您正在尝试在 ajax success 函数上返回一些内容。在这种情况下这是不可能的,因为 ajax 正在执行异步请求。像这样编写代码。

$.ajax({
url: 'country/get_states/',
dataType: 'json',
type: 'get',
async: true,
success: function(response){
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: substringMatcher(states)
});
},
error: function(jqxhr, textStatus, error){
console.log(error);
}
});

关于javascript - 无法使用 php 将 json 数据传递给 typeahead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41526226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com