我是使用ajax的新手。例如,在填充字段title
之后,我想在数据库中搜索特定数据并根据该输入返回更多字段。到目前为止,我只能通过按下获取数据/发布数据或提交按钮来接收/ ajax / post页面中的title
数据。在填写title
后/时,如何从Route::post
收到title
输入和数据?如果我删除了Form::model
和Form::close()
,我会点击Route::post
按钮但没有标题值,从Post data
获取我的虚拟数据,而不会刷新页面。
我知道检查title
字段涉及一些jQuery / js,但我不知道如何将title
字段实际带入我的route
进行数据库搜索和用它返回一些数据。
查看:
{!! Form::model($project = new \App\Project, ['url' => 'ajax/post', 'method' => 'post']) !!}
<!-- pass through the CSRF (cross-site request forgery) token -->
<meta name="csrf-token" content="<?php echo csrf_token() ?>" />
<!-- some test buttons -->
<button id="get">Get data</button>
<button id="post">Post data</button>
<div class="form-group padding-top-10">
{!! Form::label('title', 'Title') !!}
{!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Title']) !!}
</div>
{!! Form::submit('Submit Button', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::close() !!}
Ajax脚本:
<script>
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
function onGetClick(event)
{
// we're not passing any data with the get route, though you can if you want
$.get('/ajax/get', onSuccess);
}
function onPostClick(event)
{
// we're passing data with the post route, as this is more normal
$.post('/ajax/post', {payload:'hello'}, onSuccess);
}
function onSuccess(data, status, xhr)
{
console.log(data, status, xhr);
// JSON is deserialised into an object
console.log(String(data.value).toUpperCase())
}
$('button#get').on('click', onGetClick);
$('button#post').on('click', onPostClick);
</script>
在途中:
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);
});
答案 0 :(得分:0)
您需要的是实现jquery按键功能。
所以这是你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();
]);
}));
现在我可能会使用一个控制器而不仅仅是在路线中做所有事情,但我认为你会得到基本的想法。