简体   繁体   English

Laravel 5.3中的Ajax:不允许GET方法(405错误)

[英]Ajax in Laravel 5.3 : GET method not allowed (405 error)

I have a list of animals profiles (ID cards). 我有动物档案清单(身份证)。 When I click on one of them while logged in as an Admin, I access a page with more details and several pictures. 当以管理员身份登录时单击其中一个时,我将访问一个包含更多详细信息和几​​张图片的页面。 There, I can edit the animal profile (POST method), and I would also like to be able to delete a picture by clicking on it. 在这里,我可以编辑动物资料(POST方法),并且还希望能够通过单击图片来删除它。 I'm trying to use Ajax to do that, but I'm unable to complete the process. 我正在尝试使用Ajax来执行此操作,但是无法完成该过程。 My code so far : 到目前为止我的代码:

Route::get('/edition-adoption/{animal}', 'AnimalsController@editAdoption')
    ->where('animal', '[0-9]+');

Route::post('/edition-adoption/{animal}', 'AnimalsController@updateAdoption');

Route::get('/edition-adoption/{folder}/{file}/delete', ['uses' => 'AnimalsController@deletePicture', 'as' => 'delete']);

View : 查看:

<form role="form" method="POST" enctype="multipart/form-data" action="{{ url('/edition-adoption/{animal}') }} ">
        {{ csrf_field() }}

 /*several fields to update*/

            <div class="col-xs-11">
                <?php
                    edit_profile($animal->id);
                ?>
                <script src={{asset("/js/imageSrc.js")}}></script>
            </div> 
     /*other fields & submit button*/ </form>

Controller : 控制器:

public function editAdoption (Animal $animal) {
    return view('administration/edition-adoption',['animal' => $animal]);
}

public function deletePicture($file, $folder) {
    $path = public_path('js/slider_images/Adoption/Profile/'.$folder.'/'.$file);
    unlink($path);
}

public function updateAdoption (Request $request) {
    /*several update requests*/
}

Helper : 帮手:

function edit_profile($current_id) {


            $paths = File::Files('js/slider_images/Adoption/Profile/'.$current_id);

       if (count($paths)==0) {
        echo 
        "<p>Aucune image</p>";
       }    
           else {
        foreach($paths as $path)
                {
                $filesinfo[] = pathinfo($path);
                }

               foreach ($filesinfo as $file) {

                $current_basename = $file['basename'];

                echo 
                "<img onclick='getImgSrc(this)' width='200px' src='".asset("/js/slider_images/Adoption/Profile/".$current_id."/".$current_basename)."'/>&nbsp&nbsp";
                }
       }
}

imageSrc.js (Ajax) : imageSrc.js(Ajax):

    function getImgSrc(param){

var imgSrc = $(param).attr("src");
var myarr = imgSrc.split("/");
var arrlen = myarr.length;
var id = myarr[arrlen-2];
var myvar = myarr[arrlen-1];
var result = confirm("Voulez-vous vraiment supprimer cette image ? Cette action est irréversible.");

if (result) {

    $.ajax({
          url: 'delete',
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
          data: {'folder': id, 'file' : myvar},
          success: function (response) {
             alert('Image supprimée !');
          },
          error: function () {
             alert('Erreur. Veuillez réessayer.');
          }
        });
    }
}

The confirmation alert works fine, but when I click on OK, the following exception appear : 确认警报工作正常,但是当我单击“确定”时,出现以下异常:

GET http://localhost/sites/(...)/public/edition-adoption/delete?folder=foldername&file=filename.jpg 405 (Method Not Allowed) GET http:// localhost / sites /(...)/public/edition-adoption/delete?folder=foldername&file=filename.jpg 405(不允许使用方法)

Any idea(s) on how to solve this problem? 有关如何解决此问题的任何想法?

Finally solved it thanks to a friend. 终于解决了,感谢一位朋友。 It appears the order of the parameters ( $folder , $file ) in the Controller mattered. 看来控制器中的参数顺序( $folder$file )很重要。 They were in the expected order for the url/route ( /edition-adoption/{folder}/{file}/delete ), BUT they were swapped in the path (I expected http://localhost/sites/(...)/public/edition-adoption/foldern‌​ame/filename.jpg/del‌​ete and got http://localhost/sites/(...)/public/edition-adoption/filen‌​ame.jpg/foldername/del‌​ete ; which explained the 404 error). 它们按照预期的url / route顺序( /edition-adoption/{folder}/{file}/delete ),但是它们在路径中被交换了(我期望使用http://localhost/sites/(...)/public/edition-adoption/foldern‌​ame/filename.jpg/del‌​ete并获得http://localhost/sites/(...)/public/edition-adoption/filen‌​ame.jpg/foldername/del‌​ete ;解释了404错误)。 I changed public function deletePicture($file, $folder) to public function deletePicture($folder, $file) and now it works fine! 我将public function deletePicture($file, $folder)更改为public function deletePicture($folder, $file) ,现在可以正常使用了! I also added $(param).hide(); 我还添加了$(param).hide(); in the Ajax success to hide the deleted picture without having to refresh the page. 在Ajax中成功隐藏已删除的图片而不必刷新页面。 Anyway, thanks to @aynber and @AlexBlex for their advice! 无论如何,感谢@aynber和@AlexBlex的建议!

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

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