2016-10-01 54 views
0

我使用laravel 4,我想用ajax发送到控制器的请求,当我点击链接:内部服务器错误阿贾克斯Laravel

HTML:

<a class='btn btn-primary signup ' id="btnDialog" 
onClick='ajouter({{$data->id_facture}});'> Ajouter à la lise de paiement</a> 

但我总是得到错误柱500(内部服务器错误)

的javascript:

<script type="text/javascript"> 

function ajouter(id){ 

    $.ajax({ 

     url:'/ajouter/'+id, 
     dataType: 'JSON', 
     type: 'post', 

     success:function(data){ 

     if(data == 'ok'){ 
      alert('added to the list'); 
     } else { 
      alert('error'); 
     } 
    } 
    }); 
    return false; 
} 

</script> 

控制器:

public function ajouter($id=0){ 

    //return json_encode('ok'); 
    if($facture = Facture::find($id)) 
    { 
     $item = new List($id); 
     Session::put('list',$item); 
     return json_encode('ok'); 
    } 
    else 
     return json_encode('error'); 
} 

顺便说一句,我做了下面的代码一个简单的测试,它的工作:

的javascript:

<script type="text/javascript"> 

function ajouter(id){ 

    $.ajax({ 

     url:'/ajouter/'+id, 
     dataType: 'JSON', 
     type: 'post', 

     success:function(data){ 

      console.log(data); 
     } 
    }); 

    return false; 
} 

</script> 

控制器:

public function ajouter($id=0) 
{ 
    return json_encode('ok'); 
} 
+0

尝试检查你得到你的500种状态是什么错误。也许它会帮助你认识到什么是问题。您可以在浏览器中的开发人员工具的Network选项卡的帮助下做到这一点 – Silwerclaw

+0

在您的'ajax'中,您在'url'中传递了id,但是我看不到您在控制器中获得了该Id,所以当您正试图取得你的纪录,这将不会成功。 – Franco

回答

0

你的Ajax请求

$.ajax({ 
    url: '/ajouter',  
    type: 'GET', 
    data: "id=" + id, 
    dataType: "JSON", 
    success: function(data, textStatus, jqXHR) 
    { 
    if(data !="") 
    {    
     console.log(data);    
    } 

    }, 
    error: function(jqXHR, textStatus, errorThrown) 
    {    
    //alert(); 
    } 
}); 

这是你的控制器

public function getAjouter() 
{ 
    $id = Input::get('id'); 
    $facture = Facture::find($id); 
    if(count($facture) > 0) 
    { 
    $item = new List($id); 
    Session::put('list', $item); 
    return json_encode('ok'); 
    } 
    else { 
    return Response::json(array('error' => 'Error message'), 401); 
    } 
}