我是laravel的新手,我想从数据库中获取数据并使用ajax在Alert上显示它
我的路线:
Route::get('getforajax/{id}','Home@getforajax');
我的控制器:
public function getforajax ($id)
{
$result=DB::select('select * from employees where empid =?',[$id]);
return $result;
}
我的看法:
$('#empid1').keyup(function() {
$.ajax({
url: 'getforajax/3',
type: 'GET',
data: data,
dataType: 'json',
success: function (data) {
alert(data.empid);
}
});
});
您可以从控制器返回json。
return response()->json($result, 200);
但是,结果将是查询中所有结果行的数组。因此,即使您期望从查询中获得单个结果,它仍然会为您提供单个条目的数组。
[
[
id => something,
name => something
]
]
此外,您可以改进如下:
在您的javascript中,您需要执行以下操作:
data[0].empId
但是,您需要确保数据存在。使用雄辩模型从Id加载条目:
$result = Employee::findOrFail($employeeid);
然后你直接做:
alert(data.empid);
你应该试试这个:
use App\Employee; //employee table's model
public function getforajax ($id)
{
$result=Employee::find($id);
return $result;
}