使用数据库在laravel中自动填充文本字段 [英] Autocomplete text field in laravel using database
问题描述
表单cole:
>
控制器方法代码:
路线:
当我在链接上搜索时,我得到如下的查询结果:
>
显示结果:
[{id:1,value:sourav hossen},{id:2,value:sourav hossen}, {id:3,value:sourav hossen},{id:4,value:ab},{id:5,value:aa}]
我试图用jquery ajax做,它的工作。
首先,你应该在下面的代码之前包含一个jquery库。
您视图中的JavaScript代码应为:
< script>
$(document).ready(function(){
$('#q')。keyup(function(){
var q = $(this).val b $ b if(word.length> 3){
$ .ajax
({
type:GET,
url:test2,
data:{q:q},
contentType:json,
cache:false,
success:function(data,status,xhr)
{
$('#q')。val(data [0] .value);
}
});
}
});
});
< / script>
在控制器中,您应该得到ajax数据
public function autocomplete(Request $ request)
{
$ input = $ request-> all();
$ term = $ input ['q'];
$ result = array();
$ queries = ...(任何你喜欢的)
- > take(5) - > get()
foreach($ queries as $ query)
{
$ result [] = ['id'=> $ query-> id,'value'=> $ query-> firstname。''。$ query-> lastname];
}
return response() - > json($ result);
}
尝试此操作,如果发现任何困难,在这里。
I am trying to make a autocomplete form like below but the form do not show the suggestion as my database query is ok.
Form cole:
Controller method code:
Routes:
When I search on the link I get the query result like this:
Shows the result:
[{"id":1,"value":"sourav hossen"},{"id":2,"value":"sourav hossen"},{"id":3,"value":"sourav hossen"},{"id":4,"value":"a b"},{"id":5,"value":"a a"}]
I tried to do it with jquery ajax and it worked.
First of all you should include a jquery library before the following code.
The javascript code in your view should be:
<script>
$(document).ready(function(){
$('#q').keyup(function () {
var q=$(this).val();
if(word.length>3) {
$.ajax
({
type: "GET",
url: "test2",
data: {q:q},
contentType: "json",
cache: false,
success: function(data, status, xhr)
{
$('#q').val(data[0].value);
}
});
}
});
});
</script>
In your controller you should get the ajax data
public function autocomplete(Request $request)
{
$input = $request->all();
$term = $input['q'];
$result = array();
$queries = ...(do whatever you like)
->take(5)->get();
foreach($queries as $query)
{
$result[] = ['id'=> $query->id,'value'=>$query->firstname.' '.$query->lastname];
}
return response()->json($result);
}
Try this and if you find any difficulty, i'll be here.
这篇关于使用数据库在laravel中自动填充文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!