我有一个数组,我正在其中从 API 端点获取 stdClass 对象:
foreach($searchResults->hits as $arr){
foreach ($arr as $obj) {
$fullType = $obj->_source->categories;
print_r($fullType);
}
}
这正确地为我返回了正确的列表。问题是,我在这里使用硬编码值“testProduct”查询端点:
$results = "testProduct";
$searchResults = $service->getSearch($results);
因此,这会返回整个对象中具有与 testProduct 类似内容的产品列表。
我的问题是,我正在尝试用输入值替换硬编码值。我的前端有一个输入:
<form class="uk-search" data-uk-search>
<input class="uk-search-field" type="search" placeholder="search products...">
</form>
我试图在这里执行自动完成功能,以便当用户在输入中键入时,我运行 $searchResults,并且我会将上面的 $fullType 放入输入的结果列表中。
我怎样才能正确地做到这一点?
更新:
当我输入内容时,我的控制台会打印每次击键的成功,因此我知道该帖子是正确的。我应该如何处理让它返回 $searchResults 的结果?假设我想为调用中的每次击键console.log $searchResults?
Controller .php
public function autoComplete(Request $request)
{
$search_result = $request->search_result;
$service = new service();
$searchResults = $service->getSearch($search_result);
}
view.blade.php
<script type="text/javascript">
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
type: "POST",
success: function(response){
console.log("success");
}
});
}
});
</script>
最佳答案
使用 JQuery 将 oninput 事件处理程序添加到输入框:
//Place this in the $(document).ready() of your script
//Adds the event handler for input of the textbox
$('.uk-search-field').on('input', function(){
//If there is no input yet, or they deleted the text, don't do anything
if($(this).val() === ''){
return;
}else{
//Call your server side method here, first get the value of the input box
const searchValue = $(this).val(); //"this" refers to the input box at this point
//to use ajax, see below
$.ajax({ url: "yourServersideUrl",
type: "POST",
data: { serverSideMethodParameterName: searchValue}, //Data to pass to server
success: function(data){ //Deserialize data and populate drop down },
error: function(jqXHR, exception){ //Handle exception }
}});
}
});
关于javascript - 数组结果,用于输入自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52046505/