Javascript 数组结果,在输入中用于自动完成
我有一个数组,从API端点截取stdClass对象:Javascript 数组结果,在输入中用于自动完成,javascript,php,html,arrays,autocomplete,Javascript,Php,Html,Arrays,Autocomplete,我有一个数组,从API端点截取stdClass对象: foreach($searchResults->hits as $arr){ foreach ($arr as $obj) { $fullType = $obj->_source->categories; print_r($fullType); } } 这正好为我返回了一个正确的列表。问题是,我在这里使用ha rdcoded值testProduct查询端点: $results = "testProduc
foreach($searchResults->hits as $arr){
foreach ($arr as $obj) {
$fullType = $obj->_source->categories;
print_r($fullType);
}
}
这正好为我返回了一个正确的列表。问题是,我在这里使用ha rdcoded值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>
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 }
}});
}
});
听起来像是Ajax和oninput事件的工作。所以我会将结果集传递给oninput如果我了解您想要的行为,您想向服务器发送一些输入值,以过滤API返回的一些结果,如果您想在文本框上输入的每一个按键上执行此操作,您需要将事件侦听器附加到event oninput的输入,在事件处理程序函数中,通过ajax将输入框的值传递给服务器,在ajax成功后,将结果附加到未链接的列表或下拉列表中以供选择。我想我现在可以理解了。很高兴听到这个消息,这里有一些链接可能有助于使用oninput事件,以及如何使用Ajax调用php方法。如果你在看了这些之后需要更多的帮助,让我知道,我可能会给你举个例子。
//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 }
}});
}
});