Search code examples
javascriptjsonp

Requesting data from JSONP


I am currently experimenting with JSONP using native JavaScript. I am trying to create an application that reads data from a JSONP link. Here is the JSfiddle. At present I am receiving an error in my console, where it seems to have an issue with the link requested. Below I have submitted a snippet of my code:

function readResponse(resonse) {
  document.getElementsByTagName('div')[0].innerHTML = resonse.feed.entry.length + ' entries retured';
 console.log(resonse);
}

(function(){
  var src = '',
  script = document.createElement('script');
 script.src = src;
  document.body.appendChild(script);
  }) ();

Either I'm missing something out or I'm doing something completely wrong?


Solution

  • We need a callback method for jsonp request else it will throw a syntax error. when i run it i checked the response object does not have a feed property

    resonse.feed is undefined.
    

    It has the marker property. I tried below and it started working.

    window.readResponse = function(resonse) {
        console.log(resonse);
      document.getElementsByTagName('div')[0].innerHTML = resonse.markers.length + ' entries retured';
      console.log(resonse);
    };
    
    (function(){
      var src = "http://digitaslbi-id-test.herokuapp.com/bus-stops?northEast=51.52783450,-0.04076115&southWest=51.51560467,-0.10225884&callback=readResponse"
      ;
        var script = document.createElement('script');
    
      script.src = src;
        script.async = true;
      document.body.appendChild(script);
    }) ();