php laravel 5 简单的ajax从数据库中检索记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30154112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel 5 simple ajax retrieve record from database
提问by Juliver Galleto
How can I retrieve data using ajax? I have my ajax code that I've been using in some of my projects when retrieving records from database but dont know how to make it in laravel 5 because it has route and controller.
如何使用ajax检索数据?我有我的 ajax 代码,我在从数据库中检索记录时一直在我的一些项目中使用它,但不知道如何在 laravel 5 中制作它,因为它有路由和控制器。
I have this html
我有这个 html
<select name="test" id="branchname">
<option value="" disabled selected>Select first branch</option>
<option value="1">branch1</option>
<option value="2">branch2</option>
<option value="3">branch3</option>
</select>
<select id="employees">
<!-- where the return data will be put it -->
</select>
and the ajax
和阿贾克斯
$("#branchname").change(function(){
$.ajax({
url: "employees",
type: "post",
data: { id : $(this).val() },
success: function(data){
$("#employees").html(data);
}
});
});
and in my controller, I declared 2 eloquent models, model 1 is for branchname table and model 2 is for employees table
在我的控制器中,我声明了 2 个 eloquent 模型,模型 1 用于分支名称表,模型 2 用于员工表
use App\branchname;
use App\employees;
so I could retrieve the data like (refer below)
所以我可以检索数据(请参阅下文)
public function getemployee($branch_no){
$employees = employees::where("branch_no", '=', $branch_no)->all();
return $employees;
}
how to return the records that I pulled from the employees table? wiring from routes where the ajax first communicate to controller and return response to the ajax post request?
如何返回我从员工表中提取的记录?从 ajax 首先与控制器通信并返回对 ajax post 请求的响应的路由进行布线?
any help, suggestions, recommendations, ideas, clues will be greatly appreciated. Thank you!
任何帮助、建议、建议、想法、线索将不胜感激。谢谢!
PS: im a newbie in Laravel 5.
PS:我是 Laravel 5 的新手。
回答by The Alpha
At first, add following entry in your <head>
section of your Master Layout
:
首先,在您的<head>
部分添加以下条目Master Layout
:
<meta name="csrf-token" content="{{ csrf_token() }}" />
This will add the _token
in your view so you can use it for post and suchlike
requests and then also add following code for global ajax setting in a common JavaScript
file which is loaded on every request:
这将_token
在您的视图中添加 ,以便您可以将其用于post and suchlike
请求,然后还在JavaScript
每个请求加载的公共文件中添加以下用于全局 ajax 设置的代码:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
So, you don't need to worry or add the csrf_token
by yourself for methods who require this _token
. Now, for a post request you may just use usual way to make an Ajax
request to your Controller
using jQuery
, for example:
因此,csrf_token
对于需要 this 的方法,您无需担心或自行添加_token
。现在,对于 post 请求,您可以使用通常的方式向using发出Ajax
请求,例如:Controller
jQuery
var data = { id : $(this).val() };
$.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"})
// ...
});
Here, url
should match the url
of your route declaration for the employees, for example, if you have declared a route like this:
在这里,url
应该与url
员工的路线声明相匹配,例如,如果您已经声明了这样的路线:
Route::post('employees/{branch_no}', 'EmployeeController@getemployee');
Then, employees
is the url
and return json
response to populate the select
element from your Controller
, so the required code for this (including javaScript) is given below:
然后,employees
就是url
和返回json
响应,为select
从你的元素Controller
,所以这(包括JavaScript)所需的代码如下:
$.post('/employees/'+$(this).val(), function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
$.each(response.employees, function(i, employee){
$('<option/>', {
value:employee.id,
text:employee.title
}).appendTo(branchName);
})
}
}, 'json');
From the Controller
you should send json_encoded
data, for example:
从Controller
你应该发送json_encoded
数据,例如:
public function getemployee($branch_no){
$employees = employees::where("branch_no", $branch_no)->lists('title', 'id');
return response()->json(['success' => true, 'employees' => $employees]);
}
Hope you got the idea.
希望你有这个想法。
回答by umesh kadam
First check url of page from which ajax call initiates
example.com/page-using ajax
首先检查 ajax 调用发起的页面的 url
example.com/page-using ajax
In AJAX
If you call $.get('datalists', sendinput, function())
You are actually making GET request to
example.com/page-using ajax/datalists
在 AJAX 中,
如果您调用$.get('datalists', sendinput, function())
您实际上是在向
example.com/page-using ajax/datalists
In RoutesRoute::get('page-using-ajax/datalists', xyzController@abc)
在路线中Route::get('page-using-ajax/datalists', xyzController@abc)
In Controller Method
在控制器方法中
if (Request::ajax())
{
$text = \Request::input('textkey');
$users = DB::table('datalists')->where('city', 'like', $text.'%')->take(10)->get();
$users = json_encode($users);
return $users;
}
In Ajax Success Function
在 Ajax 成功函数中
function(data) {
data = JSON.parse(data);
var html = "";
for (var i = 0; i < data.length; i++) {
html = html + "<option value='" + data[i].city + "'>";
};
$("#datalist-result").html(html);
}
回答by Vladimir Djukic
Add in your route:
在您的路线中添加:
Route::post('employees', [
'as' => 'employees', 'uses' => 'YourController@YourMethod'
]);
Ajax:
阿贾克斯:
Change:
url: "employees"
to:
url: "/employees"