首页 > 解决方案 > response.forEach(function(data) 其中 response 是一个 json 双向

问题描述

最初我有这个:

在我的 php 控制器中,我有一个返回 Javascript 中的“url”变量的函数(下一个):

/*$datos is an array like this:
array:2976 [
    0 => {#1827
        +"date": "2018-08-01"
        +"time": "00:00:00"
    }
    1 => {#1828
        +"date": "2018-08-01"
        +"time": "00:15:00"
    }]
*/

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

然后在Javascript中,我使用returnurl

$.get(url, function(response){
    response.forEach(function(data){
    console.log(data);

console.log 显示:

    {fecha: "2018-08-01", hora: "00:00:00"}
    {fecha: "2018-08-01", hora: "00:15:00"}

没关系,但是现在,在 php 中,我必须像这样将两个 json 放在一起:

$datos = array(response()->json($datos_a), response()->json($datos_b));
return response()->json($datos);

$datos_a 和 $datos_b 就像示例的第一个数组。

那么,如何在 javascript 中循环输入新的响应?我期待类似的东西:

$.get(url, function(response){
    response["0"].forEach(function(data){
        console.log(data);}
    response["1"].forEach(function(data){
        console.log(data);}

当然这是错误的,但我对所有的数组、json 结构感到困惑。

标签: javascriptphp

解决方案


尝试这样的事情:

// PHP
$datos = [$datos_a, $datos_b];
return response()->json($datos);

// JS
$.get(url, function(response) {
  response.forEach(function(dataSet) {
    dataSet.forEach(function(data) {
      console.log(data);
    }
  });
});

基本上,有了这个(从你的尝试):

$datos = array(response()->json($datos_a), response()->json($datos_b));
return response()->json($datos);

...您对数据进行两次 JSON 编码(每个数据集一次,最后一次)。您只需要编码您想要返回的最终值(输出)。


推荐阅读