未定义的长度JSON AJAX返回

时间:2014-09-26 23:20:44

标签: javascript jquery html ajax json

我收到错误:

  

未捕获的TypeError:无法读取属性'长度'未定义的

当我尝试通过AJAX访问我的JSON时。

我仔细检查了JSON进度,它是response->work正确的。

唯一的时间'数据'在本节中使用。

这会是问题吗?还是我的过程图像功能?

          $.getJSON(url, function(data) {
                    $('#output').empty();

                    $.each(data.response.zone[0].records.work, processImages);

                    console.log(data);

                    printImages();
                });

处理图像功能:

function processImages(index, troveItem){
      for(var i in availableImages){
        if(troveItem.identifier[0].value.indexOf(availableImages[i].url_pattern) >= 0){
          console.log("Trove URL "+troveItem.identifier[0].value+"  Pattern: "+availableImages[i]["url_pattern"]);
          availableImages[i].numImages++;
          availableImages.totalimages++;
          availableImages[i]["images"].push(troveItem.identifier[0].value);
        }
      }
  }

整个代码供参考:

<!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>

    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/js/bootstrap.min.js"></script>

    <title>Supernatural Guide Map</title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>
    <script type="text/javascript">
    //<![CDATA[

    var customIcons = {
      Ghost: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
      },
      UFO: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
      },
      Yowie: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
      },
      Other: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png'
      }
    };

    var apiKey = "5d288qp21m735ekv";

    var availableImages = { 
                  "nla": {
                    "numImages":0,
                    "url_pattern":"nla.gov.au",
                    "images":[]
                  },
                  "totalimages":0,
                  };
    var url_patterns = ["nla.gov.au"];

    function load() {


      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(-25.3080, 134.1245),
        zoom: 3,
        mapTypeId: 'roadmap'
      });
      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP file
      downloadUrl("phpsqlajax_genxml2.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var description = markers[i].getAttribute("description");
///trove//
          resetImageData();
          //get input vals
//utf encoding// not sure if need tim etc and replace //if statement here for address or name
          var searchTerm = markers[i].getAttribute("name");//.val().trim();
          searchTerm = searchTerm.replace(/ /g,"%20");
          var sortby = "relevence";

          // create search query
          var url = "http://api.trove.nla.gov.au/result?key=" 
          + apiKey + "&l-availability=y%2Ff&encoding=json&zone=picture" 
          + "&sortby=relevance&n=100&q=" + searchTerm + "&callback=?";
          //print JSON object
          //console.log(url);
          //get the JSON information we need to display the images
          $.getJSON(url, function(data) {
            $('#output').empty();

            $.each(data.response.zone[0].records.work, processImages);

            console.log(data);

            printImages();
          });          



          var iwContent = "<b>" + name + "</b> <br/>" + address;
          var contentString = '<div id="content">'+
      //'<div id="siteNotice">'+
      //'</div>'+
      '<h1 id="firstHeading" class="firstHeading">'+name+'</h1>'+
      '<div id="bodyContent">'+
      '<p>'+'<i>'+address+'<i>'+
      '<p>'+'<i>'+type+'<i>'+
      '<p>'+description+'</p>'+
      //'<img id="output">'+
      '<div id="output">'+'</div>'
      '</div>'+
      '</div>';

          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });
          bindInfoWindow(marker, map, infoWindow, contentString);//iwContent);
        }
      });
    }

    function bindInfoWindow(marker, map, infoWindow, contentString) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(contentString);
        maxWidth: 500;
        infoWindow.open(map, marker);
      });//addmarker will go here
      google.maps.event.addListener(marker /*map*/, 'rightclick', function(){
        infoWindow.setContent(iwContent);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}

    //]]>




///TROVE///////NEED TO INCORPOATE FLICKR//also when write is implemented, write image url for quick to db loading


      function processImages(index, troveItem){
          for(var i in availableImages){
            if(troveItem.identifier[0].value.indexOf(availableImages[i].url_pattern) >= 0){
              console.log("Trove URL "+troveItem.identifier[0].value+"  Pattern: "+availableImages[i]["url_pattern"]);
              availableImages[i].numImages++;
              availableImages.totalimages++;
              availableImages[i]["images"].push(troveItem.identifier[0].value);
            }
          }
      }

      function printImages(){
        $("#output").append("<h3>Image Search Results</h3>");
        for(var i in availableImages){
          if(availableImages[i]["url_pattern"]=="nla.gov.au" && availableImages[i]["numImages"]>0){
            printNLAImages();
          }
        }

      }

      function printNLAImages(){
        $("#output").append("<h3>National Library of Australia</h3><p>"
            +availableImages["nla"]["numImages"]+" images found from <a href='http://"
            +availableImages["nla"]["url_pattern"]+"'>"
            +availableImages["nla"]["url_pattern"]+"</a></p>");

        for (var i in availableImages["nla"]["images"]){
          $("#output").append("<img src='"+availableImages["nla"]["images"][i]+"-v'>");
        }
      }

      function resetImageData(){
        availableImages.totalimages = 0;
        for (var i in availableImages){
          availableImages[i].numImages = 0;
          availableImages[i]["images"] = [];
        }
        //console.log(availableImages);
      }

      // from http://css-tricks.com/snippets/javascript/get-url-variables/
      function getQueryVariable(variable, url)
      {
             var query = url.split("?");
             var vars = query[1].split("&");
             for (var i=0;i<vars.length;i++) {
                     var pair = vars[i].split("=");
                     if(pair[0] == variable){return pair[1];}
             }
             return(false);
      }







  </script>

  </head>

  <body onload="load()">
    <div id="map" style="width: 1000px; height: 600px;"></div>
  </body>

</html>

0 个答案:

没有答案