Question

I am using the following code to do the cross domain AJAX request with YQL :

function requestCrossDomain( site, callback ) {

function cbFunc(data) {
// If we have something to work with...
alert("inside call back");
if ( data.results[0] ) {
    // Strip out all script tags, for security reasons.
    // BE VERY CAREFUL. This helps, but we should do more. 
    data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');

    // If the user passed a callback, and it
    // is a function, call it, and send through the data var.
    if ( typeof callback === 'function') {
        callback(data);
    }
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}   
// If no url was passed, exit.
if ( !site ) {
    alert('No site was passed.');
    return false;
}

// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';

// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );
console.log("outside call back");

}

and calling the above as follow :
requestCrossDomain('http://www.cnn.com', function(results) {
alert(results);
});

When i am running the above code in firefox, although response (in firebug console) is showing the content of website inside callback function (cbFunc) yet it is showing nothing as alert.
Also the result of console.log("inside call back") at line 5 is not printing in firebug console.

can anyone suggest me where things are going wrong or any explanation for above ?
btw i have already gone through :
http://tek-insight.blogspot.in/2010/05/cross-domain-ajax-request-proxy-json.html http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/ Possible explanation in related stackoverflow questions.

Était-ce utile?

La solution

$.getJSON accepts as callback function for 'success' response. But if error were returned (404, 500, etc) then it will not call this function.
You need to add extra functions in order to catch other scenarios of responses:

$.getJSON( yql, cbFunc)
  .done(function() { console.log( "second success" ); })
  .fail(function(jqxhr, textStatus, error) { console.log( "error", textStatus, error ); })
  .always(function() { console.log( "complete" ); });
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top