??yy 2016-11-26 20:38 采纳率: 0%
浏览 28

在laravel中使用Ajax

I'd like to know if it's possible to use Ajax with Laravel without writing the code inside a .js file.

Script.js

$('#selectSemestres').change(function(obj){
        var anoSemestre = $(this).val();
        $.ajax({
            type: 'GET',
            url: '',
            data: ...

        });
    })  

I don't know how to get the URL that I want (which is my currently page,
I just want to change the < select> value then reload the data that's already shown on the page).

Do I have to write the ajax inside my .php files? Is this a 'good practice'?
I'm asking this because I already have another script inside that same .php file.

Update

Following the answer posted by @ohgodwhy
Now nothing happens when the ajax executes.

It hits the success code but nothing happens, the URL does not change. Is it because I'm redirecting to the same page am at?

file.php

<script type="text/javascript">
    $('#selectSemestres').change(function(obj){
        var anoSemestre = $(this).val();
        $.ajax({
            type: 'GET',
            url: '{{ route('professor') }}',
            data: { anoSemestre: anoSemestre },
            success: function(){
                console.log('HELLO WORLD');
            }

        });
    })
</script>  

MyController:

public function getProfessorList()
    {
        $professor = Professor::all();
        if( Request::ajax() )
        {
            echo 'yolo';
        }
        $semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
        return View::make('professor', compact('professor', 'semestres'));
    }
  • 写回答

1条回答 默认 最新

  • weixin_33699914 2016-11-26 21:13
    关注

    What I usually do is add a @yield('scripts') section to my layout that I extend.

    Then in the child templates that require specific JS, I'll add that in there.

    @section('scripts')
         <script>
             //your javascript here.
         </script>
    @endsection
    

    There is 1 caveat however. If you use an @include from within a child template, and that included file has it's own javascript, it must invoke the parent first, like this:

    @section('scripts')
        @parent
        <script>
    
        </script>
    @endsection.
    
    评论

报告相同问题?