简体   繁体   中英

Parse array string to array object in Javascript

I have a page method which returns a list of integers using jQuery.ajax(); .

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

This is the result in Console

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]

I would like to stay away from trimming the square brackets and using split to then populate an array.

All I want is to be able to run

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

But in my case it prints each character, not each number.

Here's the page method if anyone is curious

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);

You should deserialize the javascript array into an actual javascript object.

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

Here's an implementation of JSON.parse

  • Why don't you just return a JSON object from the server.
  • Set the content type to application/json.
  • With the jQuery Ajax call set dataType to json.

And jQuery will parse everything for you. All you would need to do is data.yourArrayName to get the data.

I think if you set dataType:json it will parse the response as json.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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