gpt4 book ai didi

php - JQuery 自动完成,用 pHp json 中的数据填充

转载 作者:行者123 更新时间:2023-12-01 06:35:21 25 4
gpt4 key购买 nike

我正在从 php 返回一个 JSON 编码数组:echo(json_encode($data));,我希望它能够填充 JQuery 自动完成的建议框。我正在使用这个:

$("#field").autocomplete({
source : "SearchTest.php",
maxLength: 5
});

不知道为什么这不起作用。每次按键后,我都会检索数据并用该数据填充建议框,我不希望自动完成为我排序和选择,我正在服务器端进行。目前它只是一个字符串列表。能够自定义数据的呈现方式也很好。

编辑:更改帖子来源:

$("#field").autocomplete({
source : function(request, response) {
$.post("SearchTest.php", request, response);
},
maxLength : 5
});

现在收到此错误:

Uncaught TypeError: Cannot use 'in' operator to search for '1240' in 
Notice: Undefined index: field in /.../SearchTest.php on line 25

第 25 行是:$what TheyWantToSearch = $_POST['field'];

最佳答案

尝试使用ajax

var searchRequest = null;
$("#field").autocomplete({
maxLength: 5,
source: function(request, response) {
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = $.ajax({
url: 'SearchTest.php',
method: 'post',
dataType: "json",
data: {term: request.term},
success: function(data) {
searchRequest = null;
response($.map(data.items, function(item) {
return {
value: item.name,
label: item.name
};
}));
}
}).fail(function() {
searchRequest = null;
});
}
});

SearchTest.php 中的 JSON 响应示例

<?php
header('Content-type: application/json');
echo '{"items":[{"name":"Ashok"},{"name":"Rai"},{"name":"Vinod"}]}';
?>

<强> Demo Fiddle

<强> Remote JSONP Demo

关于php - JQuery 自动完成,用 pHp json 中的数据填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17764554/

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