簡體   English   中英

如何從json的laravel中的數據庫中獲取數據?

[英]how to get data from database in laravel with json?

如果正在laravel 5中接收過電子郵件,我想在ajax中進行驗證。

這是我的ajax:

$.ajax({
    type: 'POST',
    url: '/EditEmail',
    data: form.serialize(),
    dataType: 'json',
    timeout: 9000,
    error:function(data) {
        //verify if the user has already been taken 
    },
    success:function(data) {
        window.location.href=window.location.href;
    }   
});

這是我的控制器中的代碼:

public function EditEmail()
{    
    if(Hash::check(Input::get('ParolaActuala'),$parola) && count(User::where('email','=',$NoulEmail)->get()) == 0 )
    {
       DB::table('users')->where ('user_id',Auth::user()->user_id)->update(array('email' => Input::get('NoulEmail')));

       return Response::json(['success' => 'request succeeded'], 200);
    }    
}

所以我已經在控制器中進行了驗證,並且用戶無法引入同一封電子郵件,但是我想知道如何將數據從控制器發送到ajax,以便我也可以在其中進行驗證。有人有解決方案嗎?

您有兩個選擇。

使用statusCode的第一個選項:

根據Ajax文檔( http://api.jquery.com/jQuery.ajax/ ),您可以執行以下操作:

statusCode: {
    200: function() {
      alert( "user found" );
    },
    404: function() {
      alert( "user not found" );
    }
 }

並在您的控制器中返回:

// user does not exist
return Response::json(['status' => 'not_found'], 404);

//or if the user does exist
return Response::json(['status' => 'found'], 200);

使用簡單json數據的第二個選擇:

$.ajax({
   type: 'POST',
    url: '/EditEmail',
    data: form.serialize(),
    dataType: 'json',
    timeout: 9000,
    error:function(data) {
       //something went wrong with the request 
    },
    success:function(data) {
        if(data['status'] == "found") {
             alert( "user found" );
        } else {
             alert( "user not found" );
        }
    }   
});

並在您的控制器中:

public function EditEmail()
{    
     if(Hash::check(Input::get('ParolaActuala'),$parola) && count(User::where('email','=',$NoulEmail)->get()) == 0 )
     {
          DB::table('users')->where ('user_id',Auth::user()->user_id)->update(array('email' => Input::get('NoulEmail')));

          return Response::json(['status' => 'not_found']);
     }    

     return Response::json(['status' => 'found']);
}

暫無
暫無

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

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