Search code examples
javascriptjqueryjsonyql

Get JSON data from external URL and insert in a div as plain text


I have written a function to display some paragraph tags from an external webpage. For some reason the results are displayed in firebug console but not showing on the web page as I wanted (blank page).

function requestCrossDomain(callback){
  var querylink = "select * from html where url='http://somedomain.com'" +  
                     " and xpath='/html/body/div/div/div[2]/div/div/div/dl'";
  var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + 
                encodeURIComponent(querylink) + '&format=json&callback?';

  $.getJSON(yql, function(data){
    if (typeof callback === 'function'){
      callback(data);
      }
   });
}

My firebug console shows the below value.

{"query":{"count":1,"created":"2013-12-23T06:31:46Z","lang":"en-US","results":{"dd":{"p":"Hills: High"}}}}

How can I modify the code to display the value of the P tag, which is "Hills: High"

I'm calling the function from HTML code and trying to display the value inside "#targetWrapper"

requestCrossDomain(function(results){
  $('#targetWrapper').html(results);
});

Solution

  • Edited to reflect a functional fiddle

    $(document).ready(function(){
      requestCrossDomain();
    });
    
    function requestCrossDomain(){
      var querylink = "select * from html where url='http://www.bom.gov.au/wa/forecasts" +  
                      "/armadale.shtml' and xpath='/html/body/div/div/div[2]/div/div" +  
                      "/div/dl'";   
    
      var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
                 encodeURIComponent(querylink) + '&format=json&callback?';
    
      $.getJSON(yql, function(data){
        $('#targetWrapper').html(data.query.results.dl.dd[0].p);
        $("#targetWrapper").append("<br/><strong>" + JSON.stringify(data) + "</strong>");
      });
    }
    

    Your data format was very much off the mark AND you cannot have two functions with the same name.