如何在.click()

时间:2016-11-09 10:05:33

标签: php ajax laravel laravel-5.2

我正在使用Laravel 5.2,我希望在用户点击添加到购物车按钮时发送book_id,但我无法这样做。

<button id="cart" class="btnbuy btn-hvr-ripple-out">ADD TO CART</button>

Ajax功能

$(document).ready(function()
{
    $("#cart").click(function(){
        $.ajax({
            type:'get',
            url: "/addcart/{id}",
            contentType:'application/json',
            data:{ id :"{{$value->book_id}}"},
                    success: function(data){
                alert(data.msg);
            }
        });
    });
});

routes.php文件

/*cart*/
Route::get('/addcart','AjaxOperationController@addcart');

控制器

public function addcart(Request $request)
{
    $id=request->id;
    if ($request->session()->has('userId')) 
    {
        $user_id=$request->session()->get('userId');
        $add_to_cart=DB::insert('insert into cart_master (user_id, book_id) values(?,?)',[$user_id,$id]);
        return response()->json('msg'=>'Product has been added to cart! :)');
    }
    else
    {
        return response()->json('msg'=>'Please Login first to access cart! :)');
    }
}

2 个答案:

答案 0 :(得分:0)

您将数据数组作为字符串而不是javascript对象发送。

data:'{"id":"{{$value->book_id}}"}', 

将其作为对象发送:

data: {
          id : "{{$value->book_id}}"
      } 

答案 1 :(得分:0)

我认为"{{$value->book_id}}"来自php。 您需要按如下方式更改代码:

Ajax电话:

$(document).ready(function()
{
    $("#cart").click(function(){
        $.ajax({
            type:'get',
            url: "addcart/",
            contentType:'application/json',
            data:{ id :"{{$value->book_id}}"},
            success: function(data){
                alert(data.msg);
            }
        });
    });
});

路线:

Route::get('addcart','AjaxOperationController@addcart');

使用:

use Illuminate\Http\Request;

控制器:

public function addcart(Request $request)
{
    $id=request->input("id");
    if ($request->session()->has('userId')) 
    {
        $user_id=$request->session()->get('userId');
        $add_to_cart=DB::insert('insert into cart_master (user_id, book_id) values(?,?)',[$user_id,$id]);
        return response()->json('msg'=>'Product has been added to cart! :)');
    }
    else
    {
        return response()->json('msg'=>'Please Login first to access cart! :)');
    }
}