简体   繁体   English

无法将 jquery ajax 响应转换为数组 javascript

[英]Unable to convert jquery ajax response to array javascript

I have an API which returns an array of format:我有一个 API ,它返回一个格式数组:

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

When I hit the service with jquery.ajax I am able to get a response当我使用 jquery.ajax 访问服务时,我能够得到响应

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

On java script when I try to check the data type of data it is of type Object.在 java 脚本上,当我尝试检查数据类型为 Object 时。 When I directly print data on console当我直接在控制台上打印数据时

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

Where as when I print with knockout.toJSON(data) or JSON.stringify(data) it returns当我使用 knockout.toJSON(data) 或 JSON.stringify(data) 打印时,它会返回

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

However I am unable to convert the response into array as I want it to be an array.但是我无法将响应转换为数组,因为我希望它是一个数组。

I even tried JSON.parse on the knockout.JSON(data), JSON.stringify(data), and directly on data but it fails.我什至在敲除.JSON(数据)、JSON.stringify(数据)上尝试了 JSON.parse,并直接在数据上但它失败了。

What is the best way to convert this to an array.将其转换为数组的最佳方法是什么。

JS has primitive data types and Objects ,since Array is not a primitive its typeof will return Object . JS 有原始数据类型和Objects ,因为Array不是原始数据,它的typeof将返回Object

You can treat your response as an array in your code,no conversion is needed.您可以将您的响应视为代码中的数组,无需转换。

Study this SO post for further info and the docs about JS data types 研究此 SO 帖子以获取更多信息有关 JS 数据类型的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM