通过AJAX在laravel中传递值

时间:2019-03-24 16:12:34

标签: ajax laravel

我正在尝试通过传递一些数据来连接数据库和管理面板。

我的控制器看起来像 //获取状态数据以通过AJAX编辑mdoal显示

public function getblogdata(Request $request){
    $bloglists   = DB::table("bloglists")
    ->select(DB::raw("*"))
    ->where('bloglists.id' , '=', $request->uid)
    ->get();
    // $country = unserialize(base64_decode($bloglists[0]->country));
    // return response()->json( $country);
    // return response()->json( $bloglists, $country);
    return response()->json( $bloglists);
}

注意:我试图在此处传递多个变量,但不能。最后只解决了一个变量。

我的Ajax看起来像

$('.edit_blog_btn').on('click', function () {
        var blog_sel = $(this).data('uid');
        // console.log($(this).data('uid'));
        if (blog_sel) {
            $.ajax({
                type: "GET",
                url: "/get_blog_data?uid="+blog_sel, 
                dataType: "json",
                success: function (res) {     
                    // console.log(res);
                    if(res){
                        $.each(res, function (key, value){
                            $("#blog-edit-title").val(value.title);
                            $("#blog-edit-c_img").empty();
                            $("#blog-edit-c_img").append('<span>Cover Image - </span><span></span><img src="/storage/cover_images/'+value.cover_img+'" alt=" " class="img-responsive" id="blog-edit-c_img"/><input name="cover_img" type="file">');
                            $("#blog-edit-url").val(value.url);
                            var country = res[0]['country'];
                            var state = res[0]['state'];
                            var sight = res[0]['sight'];
                            var tags = res[0]['tags'];
                            console.log("the country tag is " + country+ "the state tags is " +state+ "the sight tag is "+sight+ "tha tag tag is" +tags );

                        });                            
                    } else {
                        alert('Something weird just happened');
                    }
                }
            });
        } else {
            $("#blog-id").empty();
        }
    });

注意:我只想将4个变量与其他数据一起传递以显示在视图中

1 个答案:

答案 0 :(得分:0)

您应该为[key => value]返回一个return response->json()数组。

public function getblogdata(Request $request){
    $bloglists   = DB::table("bloglists")
    ->select(DB::raw("*"))
    ->where('bloglists.id' , '=', $request->uid)
    ->get();

    $country = unserialize(base64_decode($bloglists[0]->country));

    return response()->json([
        'bloglists' => $bloglists,
        'country' => $country
    ]);
}

现在,在响应后的ajax中,尝试

console.log(res.data);
console.log(response.data.bloglists)
console.log(response.data.country)