构建数组并通过响应json发送到控制器

时间:2017-08-08 08:36:09

标签: javascript arrays json laravel

我在我的控制器中构建了一个函数,它应该将数据返回给视图。 在这里,您可以在控制器中看到我的功能

public function getSpiel(){
    $spiel = Input::get(spieleID');
    $teamOutput = Spielplan::where('Spielplan_ID', '=', $spielID)->get();

    $HeimID = $teamOutput->Heim_ID;
    $GastID = $teamOutput->Gast_ID;
    $vereinNameHeim = Verein::where('Heim_ID', '=', $teamOutput->Heim_ID;)->get();
    $vereinNameGast = Verein::where('Gast_ID', '=', $teamOutput->Gast_ID;)->get();

    $array = [];
        $array [$HeimID] = [$vereinNameHeim];
        $array [$GastID] = [$vereinNameGast];

    return Responds::json($array);
}

示例数据:

data inside $teamOutput: Spielplan_ID, Heim_ID, Gast_ID = (1, 45, 35)
array should be: [45][TeamOne]; [35][TeamTwo]

现在,我想通过return responds :: json返回构建数组到我的视图。 这是接收数据的功能。

$each(data, function(index, valueData){
    $('#spiel').append('<option value="'+ $HeimID +"'>' $vereinNameHeim'</option>');
    $('#spiel').append('<option value="'+ $GastID +"'>' $vereinNameGast'</option>');
});

现在,我的问题。这是发送数组查看的正确方法吗?如何在选项值部分的ajax函数中使用数组?因为目前它不起作用。

1 个答案:

答案 0 :(得分:0)

示例:

在routes.php上:

Route::post('getsomeinfoasjson', SomeController@returnSomeJsonData)->name('ajax_request_some_json_data');

On SomeController.php:

public function returnSomeJsonData(Request $request)
{
    if ($request->isMethod('post') && $request->ajax()) {
        $validator = \Validator::make(
            [
                'category_id' => $request->category_id,
            ],
            [
                'category_id' => 'required|integer',
            ]
        );

        if ($validator->fails()) {
            $errors = $validator->errors();
            foreach ($errors->all() as $error) {
                $messages[] = $error;
            }
            $response = [
                'success' => false,
                'message' => implode('<br>', $messages),
            ];
        } else {
            $rows = SomeModel::where('category_id', category_id)->get()->toArray();

            $response = [
                'success' => true,
                'data'    => $rows,
            ];
        }
    } else {
        $response = [
            'success' => false,
            'message' => 'Invalid request',
        ];
    }

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

视图(javascript部分):

<script>
    $(document).ready(function(){
        $.ajaxSetup({ headers: {'X-CSRF-TOKEN': "{{ csrf_token() }}"} });

        $('.ajax-btn').click(function(){
            $.ajax({
                data: {
                    category_id: 1
                },
                type: 'post',
                url: "{{ route('ajax_request_some_json_data') }}",
                success: function(response) {
                    if (response.success) {
                        $each(response.data, function(index, item){
                            // item is every element on $rows, so if your model has a property called "name", you can do item.name
                        });
                    } else {
                        console.log('Error: ' + response.message);
                    }
                }
            });
        });
    });
</script>