2

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);
2
  • Why don't you just do it on the server in the first place? Seems like the logical place to do it. Commented May 3, 2011 at 1:52
  • @epascarello: Last time I checked, List<int> was an array of integers. Commented May 3, 2011 at 1:54

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Is JSON.parse a part of jQuery now?
1
  • 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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.