0

I can't loop data out from response array.

$.post(myurl , function(response){
      for (var i = 0; i < response.result.length; i++) {
         alert(response.result[i]);
      }
},"json");

result of returned json array is :

{"result":["data one","data two","data three"]}

2 Answers 2

1

You can iterate over an object's properties with a for each loop:

for (var prop in response) {
  alert(prop + ": " + response[prop]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ahhh, sorry. Misread your question at first. What you have looks like it should work, as long as the json response is as you've shown. Can you link to a live example?
This answered the question I wanted, basically I was getting undefined errors on a json response using for loop. Likely some data was not converted into an object.
0
  1. Did u try using JSON.parse to obtain your data in the JSON object format?
  2. Always use jslint to see if your JSON is proper, before using JSON.parse.

EDIT : In your head tag add json2.js. Go here and download it. Then whenever u have a json string like the one in your question. Just use JSON.parse(somejsonstring);

var t = '{"result":["data one","data two","data three"]}' ; //Response Text
var p = JSON.parse(t); //p.result[0] will give u "data one"

2 Comments

How should I use JSON.parse? Could u plz write it for sample?
var t = '{"result":["data one","data two","data three"]}' ; //Response Text var p = JSON.parse(t); //p.result[0] will give u "data one" ya .. it works great.Thz K.A.G

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.