簡體   English   中英

內部服務器錯誤500 Laravel 5.4 AJAX

[英]Internal server error 500 Laravel 5.4 AJAX

我正在使用laravel 5.4,我想創建可以將數據發布到服務器的AJAX,但出現此錯誤消息

加載資源失敗:服務器響應狀態為500(內部服務器錯誤)

https://i.stack.imgur.com/gjIbU.png

這是我的AJAX

$('#testAjax').on('click',function(){
$.post('{{ route('edit') }}',{body:'string',_token:'{{ Session::token() }}'},function(data){
    console.log(JSON.stringify(data));
  });
});

我的路線

Route::post('/edit',[ 'uses'=>'AjaxController@getProfessions', 'as'=>'edit']);

我的控制器

public function getProfessions(Request $request)
{
  $this->validate($request, [
        'body' => 'required'
    ]);
    $p = profession::where('categories_id'=>$request['postId']);
    return response()->json(['new_body' => 'Server'], 200);
}

目前,我只希望來自服務器的響應“服務器”,而不是來自ajax的“字符串”,所以我知道它來自服務器

首先,Laravel中的良好實踐表明我們應該使用大寫字母表示模型名稱的首字母,這也許是您的問題。 嘗試更改它。

Profession::where...

其次,您不處理錯誤響應,應該在Javascript中添加一個函數來處理它,如下所示:

error: function(data) {
    console.log(data)
}

第三,您嘗試從請求中獲取postId ,但沒有發送它。

請更改您的代碼,讓我們知道結果。

您使用的$ .post錯誤,請嘗試以下操作:

$.post( "{!! route('edit') !!}", { body:'string',_token: {!! Session::token() !!} })
  .done(function( data ) {
    console.log(JSON.stringify(data));
  });
  • 在日志文件(存儲/日志)中檢查錯誤500的文件和行。
  • 將邏輯代碼包裝到try / catch中以處理錯誤。
  • 結合使用PHPStorm和XStor等IDE和XDebug來調試請求,並檢查是否正確設置了請求的每個參數(例如令牌和字符串)。

在你的路線/ web.php中

Route::post('/edit','AjaxController@getProfessions')->name('edit');

在您的控制器中:

use Illuminate\Support\Facades\Validator;

public function getProfessions(Request $request)
{


 try {
        $validator = Validator::make($request->all(), [
                'postId' => 'required',
                'body' => 'required'
            ]
        );

        if ($validator->fails()) {
            $response=array('status'=>'error','errors'=>implode(',', $validator->errors()->all()));
            return response()->json($response, 200);
        }else{
           $profession = Profession::where(['categories_id'=>$request->input('postId')])->first();
           if($profession){
             $profession->body=$request->input('body');
             $profession->save();
             return response()->json(['profession'=>$profession], 200);
           }else{
               $response=array('status'=>'error','errors'=>'profession not found');
               return response()->json($response, 200);
            }

        }
   }catch(\Exception $e){
        $response=array('status'=>'error','errors'=>'Internal Server Error');
        return response()->json($response, 500);
  }
}

在您的編輯刀片視圖中,您正在傳遞$ profession來查看:

<meta name="csrf-token" content="{{ csrf_token() }}" />

<form>
    <input type="hidded" id="postID" name="postID" value="{{$profession->postID}}" />
    <input type="text" id="body" name="body" value="{{$profession->body}}" />
   <button type="button" id="testAjax">Submit using AJAX</button>
</form>

在你的ajax函數中:

$('#testAjax').on('click',function(){
     var postID=$('#postID').val();
     var body=$('#body').val();
     $.ajax({
          url:"{{ route('edit')}}",
          headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
          type:"POST",
          dataType:"json",
          data:{
              postId:postID,
              body:body,
          },
          success:function(response){
              console.log(response);
          },
          error:function(err){

          }
     });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM