Laravel AJAX Request not working of a restful cont

2019-09-06 14:03发布

问题:

Laravel AJAX Request not working of a restful controller of a method.

This AJAX request does not work on create method but it works on index method of a laravel resource controller.

The first link is worked as it is index method. And the second link is create method which does not work. Both code are same

http://thetoppinghouse.com/laravel/public/listing
http://thetoppinghouse.com/laravel/public/listing/create

Here you will get my code summary http://laravel.io/bin/roYBY

I have already post this question without live example here but could not get solution. Laravel Ajax request not working of a controller

Here is my AJAX code summary

// AJAX Requesst
 <script>
      $('#parent_ID').on('change',function(e){
          console.log(e);

          var cat_id = e.target.value;

          // AJAX
          $.get('ajax-subcat?cat_id=' + cat_id, function(data){
          $('#subcategory').empty();
           $.each(data, function(index, subcatObj){
           $('#subcategory').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>')

               });

            console.log(data);


          });
          });

</script>

And routes is here

// routes.php

Route::resource('listing','ListingController');
Route::get('ajax-subcat', function(){
    $cat_id = Input::get('cat_id');
    $subcategories = Subcategory::where('parent_ID', '=', $cat_id)->get();
    return Response::json($subcategories);
});

回答1:

The problem is that your javascript code is making the ajax request to ajax-subcat?cat_id=1, a relative URL. This means:

/laravel/public/listing => /laravel/public/ajax-subcat
/laravel/public/listing/create => /laravel/public/listing/ajax-subcat

Since you already have your javascript inside the blade template you can easily let Laravel generate the URL:

 // AJAX
 $.get('{{ URL::to('ajax-subcat') }}?cat_id=' + cat_id, function(data){
     $('#subcategory').empty();