自定义URL Route Laravel 5.2中的405(不允许的方法)

时间:2016-04-26 17:52:59

标签: php ajax laravel controller

我遇到了我的ajax POST请求。

  1. 我的网址如下localhost/product/list(如果点击了一行,它会通过类似localhost/product/list/edit/{id}的请求重定向到 page.edit
  2. localhost/product/list/edit/{id}收到修改请求时,响应会显示localhost/product/list/edit/update_list 405 (Method Not Allowed)之类的错误。

  3. 我很困惑为什么网址从localhost/product/list/edit/{id}更改为localhost/product/list/edit/update_list,我的意思是缺少变量/{id}

  4. 控制台始终在我的AJAX edit.js 中将此部分标记为错误。

    $.ajax({
        type:"POST",
        data: {
            'id': id,
            'judul': judulArtikel,
            'isi': isiArtikel,
             // --- till the end ---
        }
    });
    

    这是我的 load.js ,它从数据库加载数据。

    <td><a id='"+result.data[count-1].id+"'' href='list/edit/"+result.data[count-1].id+"' class='glyphicon glyphicon-pencil'></a></td>
    

    这是我的route.php

    Route::get('list/edit/{id}', 'Controller@list_to_edit');
    Route::post('/update_list', 'ProductController@update_list');
    

    这是我的控制器。

    public function list_to_edit($id){
        $artikel = Artikel::where("id","=",$id)->get();
        return view('page.edit',compact('artikel'));
    }
    

    这是我的 edit.js

    &#13;
    &#13;
    $(document).ready(function(){
    	
    		$('#isi_artikel').summernote({
    			height: 300,
    			minHeight: 400,
    			maxHeight: 400,
    			focus: true
    		});
    		
    	$('#btn_submit').click(function(e){
    		e.preventDefault();
    
    		var isiArtikel = $('#isi_artikel').summernote('code');
    		var judulArtikel = $('#judul').val();
    		var deskripsiArtikel  = $('#deskripsi').val();
    		var kategori = $('input[name="etype"]:checked').val();
    
    		if($('#inputpicture').val() == ""){
    		
    		$.ajaxSetup({
    			headers: {
    				'X-CSRF-TOKEN':$('meta[name="csrf_token"]').attr('content')
    			}
    		})
    
    		$.ajax({
    			type:"POST",
    			data: {
    				'id'		: id,
    				'judul' 	: judulArtikel,
    				'isi' 		: isiArtikel,
    				'kategori' 	: kategori,
    				'deskripsi' : deskripsiArtikel,
    				'image'		: null
    			},
    			dataType: "json",
    			url: "update_list",
    			beforeSend: function (request) {
    		        return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf_token']").attr('content'));
    		    },
    			success: function(result){
    				if(result){
    					window.location.href = "kelola";
    				}
    			},
    			error : function(jqXhr) {
    		        var errors = jqXhr.responseJSON; 
    		        //console.log(jqXhr);
    
    		        errorsHtml = "<div class='alert alert-warning text-center' role='alert'>";
    
    		        $.each( errors , function( key, value ) {
    		            errorsHtml +=  value[0] ; 
    		            //console.log(value[0]);
    		        });
    
    		        errorsHtml += "</div>";
    		  
    				$('.alerts').html("<div>gila lu</div>");
    		        $('.alerts').append(errorsHtml).fadeIn(200).fadeToggle(10000).fadeOut(50);
    		    }
    		}, "json");
    		}else{
    			var ajax = function(imageData){
    				requestUploadArtikel(judulArtikel, isiArtikel, kategori, deskripsiArtikel, imageData);
    			}
    
    		imageupload($('#inputpicture').get(0), ajax);
    		}
    							
    							
    	});
    
    	function requestUploadArtikel(judul, isi, kategori, deskripsi, imageData){
    		$.ajaxSetup({
    			headers: {
    				'X-CSRF-TOKEN':$('meta[name="csrf_token"]').attr('content')
    			}
    		})
    
    		$.ajax({
    			type:"POST",
    			data: {
    				'id'		: id,
    				'judul' 	: judul,
    				'isi' 		: isi,
    				'kategori' 	: kategori,
    				'deskripsi' : deskripsi,
    				'image'		: imageData
    			},
    			dataType: "json",
    			url: "update_artikel",
    			success: function(result){
    				if(result){
    					window.location.href = "kelola";
    				}
    			},
    			error : function(jqXhr) {
    		        var errors = jqXhr.responseJSON; 
    		        //console.log(jqXhr);
    
    		        errorsHtml = "<div class='alert alert-warning text-center' role='alert'>";
    
    		        $.each( errors , function( key, value ) {
    		            errorsHtml +=  value[0] ; 
    		            //console.log(value[0]);
    		        });
    
    		        errorsHtml += "</div>";
    		  
    				$('.alerts').html("<div>gila lu</div>");
    		        $('.alerts').append(errorsHtml).fadeIn(200).fadeToggle(10000).fadeOut(50);
    		    }
    		}, "json");
    	}
    
    	function imageupload(element, ajax){
    		console.log('testimageupload');
    		
    	    var elementId = element.id;
    
    	    if(element.files && element.files[0]){
    	        var file = element.files[0];
    	        var validFileType = ".jpg, .png, .bmp";
    	        var extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
    	        $("#"+elementId+"-show").attr('src', "");
    
    	        console.log(extension);
    
    	        //validatefile
    	        if(validFileType.toLowerCase().indexOf(extension)<0){
    	            $("#"+elementId+"-alert").show();
    	            $("#"+elementId+"-show")
    	            .attr('style', '')
    				.css('height','auto')
    	            return;
    	        }
    	        $("#"+elementId+"-alert").hide();
    
    	        //showfile
    	        var reader = new FileReader();
    	        reader.onload = function(e){
    	        	ajax(e.target.result);
    	        }
    
    	        if (reader.readAsDataURL) {reader.readAsDataURL(element.files[0]);}
    	        else if(reader.readAsDataurl) {reader.readAsDataurl(element.files[0]);}
    	        else if(reader.readAsDataUrl) {reader.readAsDataUrl(element.files[0]);}
    
    	    }
    	    else{
    	    	console.log('else');
    	        $(elementId+"-show").attr('src',"");
    	    }
    	}
    });
    &#13;
    &#13;
    &#13;

    这是 edit.blade.php

    &#13;
    &#13;
    @extends('layout.layout')
    
    @section('css')
        <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.css" rel="stylesheet">
    @stop
    
    @section('script')
        <script type="text/javascript" src="{{ asset('js/artikel/edit.js') }}"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.js"></script>
    @stop
    
    
    @section('content')
     <!-- Main Content -->
     
        <div class="container">
            <div class="row">
            <h1 class="text-center edittengah">Edit Artikel</h1>
                <div class="alerts"></div>
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                @foreach ($artikel as $a_artikel)
                <input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Judul Artikel</label>
                            <input type="text" class="form-control" placeholder="Judul Artikel" id="judul" required data-validation-required-message="Harap tuliskan judul artikel." value="{{$a_artikel->judul}}">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 controls">
                            <label for="inputpicture">Ganti Foto Artikel</label>
                            <input type="file" name="picture" class="" id="inputpicture">
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Deskripsi Artikel</label>
                            <textarea name="deskripsi" id="deskripsi" cols="70" rows="5" placeholder="Deskripsi Artikel">{{ $a_artikel->deskripsi }}</textarea>
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Isi</label>
                            <div id="isi_artikel">{!! $a_artikel->content !!}</div>
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <br>
                    <div class="row control-group">
                		 <div class="form-group col-xs-12 controls">
                         <label>Jenis Artikel</label>
                         <?PHP if($a_artikel->kategori == "umum"){?>
                                <label><input class="CBumum" type="radio" name="etype" value="umum" checked="true"> Umum </label>
                                <label><input class="CBsh" type="radio" name="etype" value="selfhelp"> Self Help </label>
                                <label><input class="CBact" type="radio" name="etype" value="activites"> Activities </label>
                            <?PHP }
                                elseif($a_artikel->kategori == "selfhelp"){
                            ?>
                                <label><input class="CBumum" type="radio" name="etype" value="umum" > Umum </label>
                                <label><input class="CBsh" type="radio" name="etype" value="selfhelp" checked="true"> Self Help </label>
                                <label><input class="CBact" type="radio" name="etype" value="activites"> Activities </label>
                            <?php } 
                                else{
                            ?>
                                <label><input class="CBumum" type="radio" name="etype" value="umum" > Umum </label>
                                <label><input class="CBsh" type="radio" name="etype" value="selfhelp"> Self Help </label>
                                <label><input class="CBact" type="radio" name="etype" value="activites" checked="true"> Activities </label>
                            <?php }?>
    	                    
    	                		
                        </div>
                    </div>
                    
                    <hr>
                    <br>
                    <div id="success"></div>
                    <div class="row">
                        <div class="form-group col-xs-12">
                            <input class="btn btn-success" id="btn_submit" type="submit">
                        @endforeach
    
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
    @stop
    &#13;
    &#13;
    &#13;

    需要你的帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

好的,我对路线的了解不多,

我的ajax网址更新:

"url" : "/update_list"

必须

"url" : window.location + "/update_list"

和我的控制器来自:

    Route::post('/update_list', 'Controller@update_post');

    Route::post('kelola/list/{id}/update_list', 'Controller@update_post');

'kelola / list / {id} / update_list'在ajax进程URL之前引用我的baseUrl