简体   繁体   中英

display JSON in laravel blade

Hey guys I'm using a rating system in my project and I'm trying to filter announcers according to their level

I used ajax for that

I get my data properly in the console( Array of objects) but I'm wondering how can I loop through them and display them in my blade?

my jquery code :

$(document).ready(function()
{
    $('.star-rating input[type=radio]').click(function() {
        var text = $(this).val();
        $.ajax({

            url: 'filterAnnouncer',
            type: 'GET',
            data: { text, },
            success: function(data)
            {
                console.log(data);
            }
        });            
    });
});

My Laravel Controller

public function handleFilterBagageAnnouncer(Request $request){
    $data = $request->text;
    $filter = BagageAnnouncement::whereHas(
        'announcement.user.profile.profileSetting',
        function ($q2) use ($data) {
            $q2->where('level',$data);
        }
    )->get();
    return json_decode($filter);
}

There is an issue in your controller function code here.

return json_decode($filter);

this is wrong. json_decode() is to convert(decode) json data to php objects .
but you need to convert(encode) php objects to json data . so

return json_encode($filter);

now in your ajax success this how you can loop

success: function(data){

    // convert json data to js objects.
    // to make your we get js objects from json data.
    var dataArray = JSON.parse(data);

    dataArray.forEach(announcer => {

        // your code goes here.
        console.log(announcer);
    });
}

use like this

success: function(data){

    // convert json data to js objects.
    // to make your we get js objects from json data.
    var dataArray = JSON.parse(data);
    items.forEach(function(item){
        $('selecter').append(item);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM