0

Firstly I'm pretty new to javascript and web development in general (I've been writing Windows apps for quite a while).

I'm pulling a JSON object array down from am external webservice and have used a php proxy to get the JSON via AJAX. I can parse the JSON object using eval() but I can't seem to iterate though the array.

Here's my onreadystatechange function...

if(this.readyState == 4)
            {
                if(this.status == 200)
                {
                    if(this.responseText != null)
                    {
                        var text = "";
                        var object = eval("(" + this.responseText + ")");

                        for (var i = 0; i < object.length; i++)
                        {
                            text+= "<p><img src=\"" + object[i].avatar_url + "\"/>";
                            text+= object[i].username + "</p>";
                        }

                        document.getElementById("content").innerHTML = text;
                    }
                }
            }

I get the error "StartTag: invalid element name" at the '<' in my for loop. The JSON is well formatted and if I run this code just as a script (i.e. without AJAX) I can iterate through the array just fine.

I'd prefer not to use any external libraries such as JQuery for now as I'm still trying to get my head around the basics.

Thanks in advance.

mister_b
  • 157
  • 2
  • 9
  • use JSON.parse(responseText) not eval. Also, whats the json you are getting back? – hvgotcodes May 18 '11 at 19:58
  • Since you're new to JavaScript I want to mention to try and avoid using `eval` if you can (and you usually can): http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea – McStretch May 18 '11 at 19:58
  • Use console.log("%o", object) with Firefox/Firebug and post the json you get back – Adrian Rodriguez May 18 '11 at 20:01
  • Being new to JavaScript I highly recommend that you have a look at http://jquery.com/ and use their library...it'll take away a lot of the browser complexities for you! Sorry that doesn't help this issue...that is unless you start using jQuery...but it really is great. – Craig May 18 '11 at 20:01
  • Place a breakpoint or write a hard `debugger;` before the `for` and inspect `object`, does it look to what you expect? The reason to not use `eval` is `JSON.parse` makes some validity/security checks before actually making an `eval` too. – Mic May 18 '11 at 20:11
  • Cheers for the comments guys. I'm aware of not using the `eval` method but I want to get my head round the basics before I move onto using libraries. I have this sorted now, I had this script within an XHTML file, when I changed it to HTML it worked fine. – mister_b May 20 '11 at 11:24

0 Answers0