0

我正在尝试向array我的控制器发送一个以保存在数据库中,如果在这种情况下我将array a string它保存到数据库中。所以当data: {'mapData' : arrayAllDrawings},它崩溃时(arrayAllDrawings beeing一个数组)。但是当它像这样的字符串被硬编码时,data: {'mapData' : 'string'},它会通过并保存在数据库中success message

storage/logs服务器抛出 500 内部服务器错误时的错误日志

[2019-03-28 08:40:09] local.ERROR: 数组到字符串转换 {"userId":1,"exception":"[object] (ErrorException(code: 0): 数组到字符串转换在 C: \Users\Merlijn\AppData\Roaming\Composer\Laravel Projects\Forum\vendor\laravel\framework\src\Illuminate\Support\Str.php:354) [stacktrace]

我尝试JS用 in 将数组变成 1 个长字符串,JS.toString()仍然给出了同样的错误。

JS 数组的样子例如:

2: Array(2)
0: "{"type":"Feature","properties":{},"geometry": 
{"type":"Point","coordinates":[4.90694,52.385973]}}"
1: {type: "Name", Status: "Insert pointer name"}
length: 2
__proto__: Array(0)
3: "{"type":"Feature","properties":{},"geometry": 
{"type":"Point","coordinates":[4.90694,52.385973]}}"
length: 4

javascript代码ajax:

function saveInDb() {
        if (typeof arrayAllDrawings !== 'undefined' && arrayAllDrawings.length > 0) {
            $.ajax({
                method: 'POST', said in the route
                url: '{{ route('map.store') }}', gave in the route
                data: {'mapData' : arrayAllDrawings},
                success: function(response){ 
                    console.log(response);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(JSON.stringify(jqXHR));
                    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                }
            });
        } else {
            alert('The map has nothing on it!')
        }
    }

控制器:

public function store(Request $request)
{
//        dd($request);
//        $mapData = Input::get('mapData');
//        dd($mapData);
    if(request()->ajax()){

        $mapData = Input::get('mapData');
        $map = new Map;
        $map->user_id = auth()->user()->id;
        $map->map = $mapData;
        $map->save();

        return response()->json(['status' => 'succes', 'message' => 'saved in database','data' => $mapData]);

    } else {

        return response()->json(['status' => 'fail', 'message' => 'this is not json']);

    }
}
4

2 回答 2

1

您可以通过使用以下方法将数组转换为字符串来轻松管理它:

json_encode($your_array); or serialize($your_array);

可以反向操作:

json_decode($string); or unserialize($string); 

关于上述功能的使用。

于 2019-03-28T09:00:40.580 回答
1

您可以将javascript数组转换为json

JSON.stringify(arrayAllDrawings)

然后你可以得到这是 json 的形式并将这个 json 转换为

json_encode(json_decode($mapData,true));

然后存入数据库。

于 2019-03-28T09:06:13.273 回答