【问题标题】:Unable to convert jquery ajax response to array javascript [closed]无法将 jquery ajax 响应转换为数组 javascript [关闭]
【发布时间】:2022-02-05 19:11:01
【问题描述】:

我有一个返回格式数组的 API:

[
  {
    "abc": "def",
    "efg": "hij"
  },
  {
    "abc": "def",
    "efg": "hij"
  }
]

当我使用 jquery.ajax 访问服务时,我能够得到响应

$.ajax({
url: URL,
type: 'GET',
dataType: 'JSON',
xhrFields: {
withCredentials: false
},
success: function (data) {
console.log(data);
},
error: function (request, error) {});

在 java 脚本中,当我尝试检查数据的数据类型时,它是 Object 类型。 当我直接在控制台上打印数据时

0: Object { "abc": "def", "egf":"ghi " }​​
​
1: Object { "abc": "def", "egf":"ghi " }​​

当我使用 knockout.toJSON(data) 或 JSON.stringify(data) 打印时,它会返回

[
  {
    "abc": "def",
    "efg": "hij"
  },
  {
    "abc": "def",
    "efg": "hij"
  }
]

但是我无法将响应转换为数组,因为我希望它是一个数组。

我什至在 knockout.JSON(data)、JSON.stringify(data) 和直接在 data 上尝试了 JSON.parse,但它失败了。

将其转换为数组的最佳方法是什么。

【问题讨论】:

  • 响应一个数组。不需要转换。看起来像an XY problem - 你正在尝试做某事,它不起作用,并且你假设这个数据不是一个数组,因此你问如何制作它。您要解决的问题是什么?为什么这个数组不起作用?

标签: javascript jquery arrays ajax knockout.js


【解决方案1】:

JS 有primitive 数据类型和Objects,因为Array 不是原始类型,所以typeof 将返回Object

您可以在代码中将您的响应视为一个数组,无需转换。

Study this SO post for further infothe docs about JS data types

【讨论】:

    猜你喜欢
    • 2014-06-09
    • 1970-01-01
    • 2016-01-14
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多