简体   繁体   中英

Requesting JSON from server and parsing in Javascript

I am trying to pull json down from my server and parse it into a Javascript object. here is what my json looks like:

{
  "tour1": [
    {
      "title": "building1",
      "description": "Tour of building1",
      "image": "Icon.png",
      "video": "tour.mp4",
      "length": "0.00",
      "version": "1.0",
      "timestamp": "1111111111"
    }
  ]
}

Here is the requst to the server:

<!DOCTYPE html>
<html>
<body>
    <h2>Parse JSON from Server</h2>
    <p id="demo"></p>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">                      </script>
    <script>
        $.ajax({
            url: "mysite.com/videos/tour.json";
        var j = [];
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'json',
        });
        window.alert(j.tour1[0].title);
    </script>
</body>
</html>

I cant understand why its not working. I am new to javascript. I appreciate any help with this issue.

I think better if you use getJson when you want to load JSON-encoded data from the server using a GET HTTP request, check example bellow :

$.getJSON( "mysite.com/videos/tour.json", function( j ) {
     alert( j.tour1[0].title );
});

Hope this helps.

Ajax call is an asynchronous call, j is not populated as soon as your ajax statement ends.

Use success handler of Ajax to alert the j (didn't tested the code)

$.ajax({
  url: "mysite.com/videos/tour.json",
  method: "GET",
  dataType: "JSON",
  success: function( data ){
    window.alert(data.tour1[0].title);
  }
});

gurvinder give the best solution, because if you are firing the ajax-request then you must catch the response, but if you make the alert in your code your request is still working and j must be undefined because it is not a global variable. there a lot of mistakes:

  1. check your ajax-synthax , because the declaration of "var j.." is wrong,
  2. never use ";" in a object declaration, always use ","
  3. in your alert you try to find a variable "j", but j don't exist, it is undefined.

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