1

I have a proxy script that outputs json data via php, and I want to be able to manipulate this data using javascript. I have the following code, but it only gets the entire json string outputted by the php script. How do I take the data and be able to access the individual objects with in this json data?

var xmlhttp;
function loadXMLDoc(url, cfunc) {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = cfunc;
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

loadXMLDoc("http://xxxxx.appspot.com/userbase_us.php?callback=userdata", function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var json = xmlhttp.responseText;
      alert(json);
  }
});
1

1 Answer 1

5

You can use the native JSON.parse method:

var json = JSON.parse(xmlhttp.responseText);

Note that since this is not supported by older browsers, you will most likely want to polyfill it.

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

1 Comment

@Mr.1.0 - Then your JSON is not valid. Update your question with an example JSON string returned by your script, or use a tool like JSON Lint to validate it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.