【问题标题】:Parse array string to array object in Javascript在Javascript中将数组字符串解析为数组对象
【发布时间】:2011-08-17 09:10:21
【问题描述】:

我有一个使用jQuery.ajax(); 返回整数列表的页面方法。

$.ajax({
    type: "POST",
    url: url,
    success: function (response) {
        console.log(typeof (response.d));
        console.log(response.d);
    }
});

这是控制台中的结果

string
[1767,3071,2744,1256,657,3374,3318,2518,3910,4107,2579,2997,1182,1260,32,3185,873,1374,35,858,3126,1911,3887,3053,298,3150,4222,2692,1397,707,3958,947,1315,4379,2265,2845,3123,3857,1140,1608,2317,2512,3280,1842,1930,4334,878,1366,522,1231]

我不想修剪方括号并使用 split 然后填充数组。

我只想跑起来

$.each(response.d, function() {
    console.log(this); // print each number in the array
});

但在我的情况下,它会打印每个字符,而不是每个数字。

如果有人好奇,这里是页面方法

Random rnd = new Random();
List<int> numbers = new List<int>();
for(int i=0; i<50; i++) {
    numbers.Add(rnd.Next(1000));
}


JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(numbers);

【问题讨论】:

  • 你为什么不在服务器上做呢?似乎是合乎逻辑的地方。
  • @epascarello:上次我检查时,List&lt;int&gt; 是一个整数数组。

标签: c# javascript jquery ajax arrays


【解决方案1】:

您应该将 javascript 数组反序列化为实际的 javascript 对象。

var responseArray = JSON.parse( result.d )
//responseObject is now a literal javascript array, so you can iterate over it as you would any other array

这是implementation of JSON.parse

【讨论】:

  • JSON.parse 现在是 jQuery 的一部分了吗?
【解决方案2】:

我认为如果你设置 dataType:json 它会将响应解析为 json。

【讨论】:

    【解决方案3】:
    • 为什么不直接从服务器返回一个JSON object。
    • 将内容类型设置为 application/json。
    • 使用 jQuery Ajax 调用将 dataType 设置为 json。

    jQuery 会为你解析一切。您需要做的就是 data.yourArrayName 来获取数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多