Saturday, March 10, 2012

Get Data using Cross-Domain Request

There is a two methods to get data from the url. one is XML and second is the Json. the xml methods is very complicated and large. that's why I started to use json format for the cross-domain request.

Create cross_domain.js file

function requestCrossDomain( site, callback ) {
     if ( !site ) {
          return false;
     }
     var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
  $.getJSON( yql, cbFunc);

  function cbFunc(data) {
     if ( data.results[0] ) {


//data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
data = data.results[0].replace(/<body>/gi,"");
           data = data.replace(/<p>/gi,"");
           data = data.replace(/<\/p>/gi,"");
           data = data.replace(/<\/body>/gi,"");
           // alert(data);
if ( typeof callback === 'function') {
callback(data);
}
}
else throw new Error('Nothing returned from getJSON.');
}
}

Create index.html


<p><label>Type a URL : </label> <input type="text" name="sitename" id="sitename" /></p>
<p><input type="submit" name="submit" id="submit" value="Cross-Domain Request" onclick="requestjson()"></p>
<div id="container"></div>


include java-script file into the Html head section
<script type="text/javascript" src="cross_domain.js"></script> 
you also need to include jquery min file to execute the jquery code.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
Create function in the head section to call the cross-domain function on button click.

<script type="text/javascript">
function requestjson(){
var path = $('#sitename').val();
requestCrossDomain(path, function(results) {     $('#container').html(results);}); return false;
}
</script>

Cheers...