Javascript 如何使用ajax检索数据,而无需进入post页面?拉维尔5号
我不熟悉使用ajax。例如,在填写字段Javascript 如何使用ajax检索数据,而无需进入post页面?拉维尔5号,javascript,php,jquery,ajax,laravel,Javascript,Php,Jquery,Ajax,Laravel,我不熟悉使用ajax。例如,在填写字段title后,我想在数据库中搜索特定数据,并基于该输入返回更多字段。到目前为止,我只能通过按“获取数据/发布数据”或“提交”按钮在/ajax/post页面中接收我的标题数据。如何在填写标题时/之后从路线::post接收我的标题输入和数据?如果我删除Form::model和Form::close()我确实会通过单击post data按钮从Route::post获取虚拟数据,而不进行页面刷新,但不带标题值 我知道检查title字段涉及一些jQuery/js,但我
title
后,我想在数据库中搜索特定数据,并基于该输入返回更多字段。到目前为止,我只能通过按“获取数据/发布数据”或“提交”按钮在/ajax/post页面中接收我的标题数据。如何在填写标题
时/之后从路线::post
接收我的标题
输入和数据?如果我删除Form::model
和Form::close()
我确实会通过单击post data
按钮从Route::post
获取虚拟数据,而不进行页面刷新,但不带标题值
我知道检查title
字段涉及一些jQuery/js,但我不知道如何实际将title
字段带入我的route
进行一些数据库搜索并返回一些数据
视图:
您需要的是实现jquerykeypress函数
这就是你的js:
$("input.title").keypress(function(){
var title = $(this).val();
// now do the ajax request and send in the title value
$.get({
url: 'url you want to send the request to',
data: {"title": title},
success: function(response){
// here you can grab the response which would probably be
// the extra fields you want to generate and display it
}
});
});
在Laravel中,除了返回json外,您几乎可以将其视为典型请求:
Route::get('/url-to-handle-request', function({
// lets say what you need to populate is
//authors from the title and return them
$title = Route::get('title'); // we are getting the value we passed in the ajax request
$authors = Author::where('title' ,'=', $title)->get();
return response()->json([
'authors' => $authors->toArray();
]);
}));
现在,我可能会使用控制器,而不仅仅是在路线内执行所有操作,但我认为您会了解基本的想法。在键入“标题”时是否要获取数据?为什么使用$.get({?使用$.post({和$.get)之间有区别吗({?。难道我们不应该使用post吗?然后我们会返回一些数据吗?@Dancia get和post的主要区别在于您对请求的处理方式。例如,每次您在google上搜索某个内容时,google都会发送一个get请求,其中包含您发送的参数并检索结果。现在,如果您注册gmail,那么这将是一个post请求谷歌没有收到任何数据。同样对于get请求,请求会出现在url中,因此如果它的敏感数据,我将始终执行post请求。
Route::get('/ajax/view', ['as' => 'home', 'uses' => 'AjaxController@view']);
Route::get('/ajax/get', function () {
$data = array('value' => 'some get');
return Response::json($data);
});
Route::post('/ajax/post', function () {
$data = array('value' => 'some data', 'input' => Request::input());
return Response::json($data);
});
$("input.title").keypress(function(){
var title = $(this).val();
// now do the ajax request and send in the title value
$.get({
url: 'url you want to send the request to',
data: {"title": title},
success: function(response){
// here you can grab the response which would probably be
// the extra fields you want to generate and display it
}
});
});
Route::get('/url-to-handle-request', function({
// lets say what you need to populate is
//authors from the title and return them
$title = Route::get('title'); // we are getting the value we passed in the ajax request
$authors = Author::where('title' ,'=', $title)->get();
return response()->json([
'authors' => $authors->toArray();
]);
}));