简体   繁体   English

如何使用ajax检索数据而无需发布页面? Laravel 5

[英]How to retrieve data using ajax and without going to post page? Laravel 5

I'm new to using ajax. 我是使用ajax的新手。 For example after field title is filled, I want to search in database for specific data and return more fields based on that input. 例如,在填写字段title后,我想在数据库中搜索特定数据并根据该输入返回更多字段。 So far I can only receive my title data in /ajax/post page by pressing get data/post data or submit button. 到目前为止,我只能通过按获取数据/发布数据或提交按钮来接收/ ajax / post页面中的title数据。 How do I receive my title input and data from Route::post while/after filling title ? 填充title时/之后,如何从Route::post接收title输入和数据? If I remove Form::model and Form::close() I do get my dummy data from Route::post without page refresh by clicking Post data button, but without title value. 如果删除Form::modelForm::close()我确实会从Route::post获取虚拟数据,而无需单击“ Post data按钮来刷新页面,但没有标题值。

I'm aware that checking title field involves some jQuery/js, but I have no idea how to actually bring that title field into my route to do some database searching and return some data with it. 我知道检查title字段涉及一些jQuery / js,但是我不知道如何将title字段实际带入我的route以进行一些数据库搜索并返回一些数据。

View: 视图:

            {!! 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: 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>

And in route: 在途中:

    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);
    });

What you need is to implement the jquery keypress function. 您需要实现jquery keypress函数。

so here is you js: 所以这是你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
        }
    });
});

as far as in Laravel you can pretty much treat it the same as a typical request except you will return json: 就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();
    ]);
}));

Now I would probably use a controller and not just do everything within the route but I think you'll get the basic idea. 现在,我可能会使用控制器,而不仅仅是在路线中做所有事情,而且我想您会明白基本的想法的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM