代码之家  ›  专栏  ›  技术社区  ›  sadmicrowave

Laravel 5“内部服务器错误”(500),Ajax表单提交

  •  1
  • sadmicrowave  · 技术社区  · 7 年前

    我对我的 ajax 在my中提交表单 Laravel 5 项目我的浏览器控制台中出现以下错误:

     Failed to load resource: the server responded with a status of 500 (Internal Server Error)
    

    我尝试了许多在其他帖子和网站上找到的建议,但都没有成功。以下是我的Ajax:

    $.ajax({'url': './subscribe' 
        ,'data' : {
                    "_token": $('meta[name="csrf-token"]').attr('content')
                    ,"email" : $('#subscribe-email-input').val() 
                }
        ,'method': 'POST' 
        ,'success': function(data){
            console.log( data );
        }
        ,'error': function(data){
            console.log( 'oops', data );
        }
    });
    

    我在我的 routes/web.php 文件:

    Route::post('subscribe', ['uses' => 'SubscribeController@validate', 'as' => 'subscribe.route']);
    

    控制器非常简单:

    class SubscribeController extends Controller
    {   
        /*
        *   Get email address from DB if exists
        *
        *   @param string email, email address to search and return data from DB
        *
        *   @returns $email
        */
        public function validate ( Request $request )
        {
            $email = addslashes($request->email) ;
    
            if ( $email ) 
            {           
                $email = \App\Subscribe::where('email', '=', $email)->get();
    
                if ( $email->isEmpty() ) 
                {
                    self::executeInsertQuery ( $email );
                    return json_encode( array('body' => 'You have subscribed!') );
                } else {
                    return json_encode( array('body' => 'You are already subscribed!') );
                }
    
            }       
        }
    }
    

    我会在 self::executeInsertQuery(...) 但考虑到 subscribe 路线似乎还没有到达 validate 方法

    如果您对如何解决此问题有任何建议,我们将不胜感激!!提前感谢您!

    3 回复  |  直到 7 年前
        1
  •  4
  •   Amr Aly    7 年前

    问题是 validate 函数是Laravel控制器中的预定义方法,因此您可以覆盖它,从而导致问题。尝试将其更改为其他内容。

        2
  •  2
  •   Hp Lam    7 年前

    尝试

    return response()->json([
        'body' => 'You have subscribed!'
    ]);
    

    https://laravel.com/docs/5.6/responses#other-response-types

        3
  •  2
  •   dimacros    7 年前
    • 首先,在不使用ajax的情况下发送表单,并验证表单是否记录了发送的数据,然后在其ajax函数中,将参数“method”:“POST”更改为“type”:“POST”,然后重试。注意:jquery 3.0之前的版本需要用类型指示,否则默认情况下它将发送GET。

    • 其次,将名称方法“validate”更改为“validateuscriber”,因为控制器类已经有了一个“validate”方法,并且通过使用两个相等的方法创建了冲突。