javascript - 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中,我使用return
它url
:
$.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 结构感到困惑。
解决方案
尝试这样的事情:
// 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 编码(每个数据集一次,最后一次)。您只需要编码您想要返回的最终值(输出)。
推荐阅读
- php - 如何使用实体引用类型以编程方式创建节点 - Drupal 8
- api - 如何使用变音符号发送 Twitter 状态更新?
- c++ - 非法将此类型用作模板中的表达式
- javascript - 如何使用 .not() 在正文中选择除一个元素之外的所有元素
- flutter - 如何处理2电话权限以获取设备的IMEI号码和手机号码?
- python - 如何修改数据集以进行训练
- solidity - 工厂错误调用的函数应该是应付的
- javascript - 函数开始使用状态之前的 Spinner(CircularProgress)
- r - 如何在 R 中使用 tryCatch 将值设置为 0?
- sql - SQL where子句在子表中查找包含混合值的记录