【问题标题】:AJAX Send array as response from LaravelAJAX 发送数组作为 Laravel 的响应
【发布时间】:2016-08-31 03:18:32
【问题描述】:

我正在尝试从 Laravel 发送对 AJAX 发布请求的响应。

public function infoRoute(Request $request)
    {
        // Get info
        $ship_id = $request->ship_id;
        $startDate = $request->datepicker_start;
        $endDate = $request->datepicker_end;

        // Get all the locations between those dates
        $routeArray = $this->measurementRepository->getCoordinates($ship_id, $startDate, $endDate);

        $ship = $this->shipRepository->getShipForId($ship_id);
        $info = $this->createRouteArrayForShip($ship, $routeArray);

        if($request->ajax()) {
            return response()->json(json_encode($info));
        }
    }

    protected function createRouteArrayForShip($ship, $routeArray)
    {
        $info['type'] = "showRoute";

        $index = 0;

        foreach($routeArray as $coordinates)
        {
            $info['info']['route']['loc'. $index] = $coordinates;
            $index++;
        }

        $info['info']['shipInfo'] = $ship;

        //dd($info);
        return $info;
    }

当我收到信息并使用 jQuery 处理它时,除了路由之外的所有内容都显示,即为空。

谢谢,

【问题讨论】:

  • 如果您使用浏览器开发工具.. 您看到响应中返回了哪些数据?
  • 你那里有一个多维数组..
  • 尝试以 JSON 格式返回
  • 至少你不需要response()->json(json_encode($info));,使用response()->json($info);
  • @Dale 我得到的是一个对象,包含一个对象“信息”和一个字符串“类型”。在“信息”中,我只得到对象 shipInfo。但是没有路线的迹象

标签: php arrays ajax laravel post


【解决方案1】:

response()->json() 方法在后台使用json_encode() PHP 函数将给定数组转换为 JSON。 因此,您应该从 response()->json() 调用中删除您的 json_encode()

基本上应该是这样的

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

【讨论】:

  • 谢谢!我已经这样做了,但它仍然无法正常工作。我认为这与$info 不包含路线坐标有关。它是空的。如果我在返回响应之前执行dd($info),则路线为空。但是当我调用函数 createRouteArrayForShip 时,它实际上将记录保存在数组中
猜你喜欢
  • 2021-03-20
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 2018-03-27
  • 1970-01-01
  • 2011-03-18
  • 2017-06-09
相关资源
最近更新 更多