如何读取 ajax 中包含多个对象的响应 laravel 5.2

how to read ajax response with multiple objects in laravel 5.2

我正在尝试通过控制器 json 响应在更改下拉列表时获取多个 eloquent 对象。

更改电影院时,应该return 从 2 个不同的表中获取 2 个对象。

控制器代码

 public function getscreen($id)
{
    $screens=Movies_screen::where('cinema_id',$id)->get();
    $showtime=Movies_showtimes::where('cinema_id',$id)->get();

    return response()->json($screens);
}

我的jqueryajax代码

 $("#cinemahall").on("change click",function(){

var cinema_id=$("#cinemahall option:selected").val();
//ajax
    $.get('/askspidy/admin/showtime/getscreen/' + cinema_id, function(data){

        $("#screenname").empty();
        $("#screenname").append('<option value=0>Select Screen</option>');

        $.each(data,function(index,screenobj){
            $("#screenname").append('<option value="' +screenobj.screen_id + '">' +screenobj.screen_name +'</option>');
        });
    });
});

上面的代码在发送单个 eloquent 对象时工作正常,即 $screens ,但正如您在代码中看到的那样,还有另一个对象,即 $showtime ,我需要发送相同的请求并阅读它在我的 jquery ajax 代码中。

我在控制器中试过

 public function getscreen($id)
{
    $screens=Movies_screen::where('cinema_id',$id)->get();
    $showtime=Movies_showtimes::where('cinema_id',$id)->get();

    return response()->json($screens,$showtime);
}

并在 jquery 代码中

 $.get('/askspidy/admin/showtime/getscreen/' + cinema_id, function(data,data2)

但 none 的解决方案有效。

Return 您在数组中的回复:

return response()->json(["screens" => $screens, "showtime" => $showtime]);

然后通过您的 GET 请求使用 JS 对象的 . 语法访问:

$.get("URL", function(data){ 
    console.log(data.screens);
    // or 
    console.log(data.showtimes);
});

您可以 return 一个数组,其索引指向不同的集合:

return response()->json(['screens' => $screens, 'showtime' => $showtime]);

在 JSON 中,这将被转换为具有两个属性的 Javascript 对象,'screens' 和 'showtime':

$.get('/askspidy/admin/showtime/getscreen/' + cinema_id, function(data) {
    console.log(data.screens);
    console.log(data.showtime);
});