简体   繁体   中英

Parsing JSON data into html page with getJSon function

I'm trying to make maybe the simplest jQuery's getJson function and I'm facing some problems..

my script:

<script>

   $(document).ready(function()
     { 
         $.getJSON('http://localhost:8000/api/tests', function(Results) 
     {
        document.write(Results.name);
        });
     });

</script>

I have tried to include jquery.js with multiple different ways. for example:

<script src="../js/jquery.js"></script>
<script src="https//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

Localhost:8000/api/tests prints out: [{"id" :1, "name":"test", "description":"testtext"}]

in app/config I have

assetic:
  assets:
    jquery: "%kernel.root_dir%/.../vendor/components/jquery/jquery.min/js"

Probably nothing to do with this but if I add - front of the jquery ERROR: "The attribute "name" must be set for path "assetic.assets"

Current result : undefined

Any tips how I make it display result as I want.. in this case instead of undefined it should be test

Hopefully you understand my question. Thanks for your time!

[{"id" :1, "name":"test", "description":"testtext"}]

That's an array containing an object.

document.write(Results.name)

That tries to treat the array as if it was the object contained it it.

You need to get at the object out of the array first.

document.write(Results[0].name)

NB:

  • By convention, variable names starting with a capital letter in JavaScript are reserved for Constructor Functions. Call your variable results instead.
  • document.write will, unless run while the document is being constructed, destroy the existing document. This is almost always undesirable. You should probably use DOM instead.

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