在Javascript中将数组字符串解析为数组对象

时间:2011-05-03 01:50:43

标签: c# javascript jquery ajax arrays

我有一个页面方法,它使用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);

3 个答案:

答案 0 :(得分:5)

您应该将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

答案 1 :(得分:1)

  • 为什么不从服务器返回JSON object
  • 将内容类型设置为application / json。
  • 使用jQuery Ajax调用将dataType设置为json。

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

答案 2 :(得分:0)

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

相关问题