使用YQL进行跨域AJAX请求时一无所获



我使用以下代码用YQL执行跨域AJAX请求:

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[^>]*>[sS]*?</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");
}

并按如下方式调用以上内容:
requestCrossDomain('http://www.cnn.com', function(results) {
alert(results);
});

当我在firefox中运行上述代码时,尽管response(在firebug控制台中)在回调函数(cbFunc)中显示了网站的内容,但它没有显示任何警报
此外,第5行的console.log("inside call back")的结果未在firebug控制台中打印

有人能告诉我哪里出了问题,或者对上面的情况有任何解释吗
顺便说一句,我已经经历了:
http://tek-insight.blogspot.in/2010/05/cross-domain-ajax-request-proxy-json.htmlhttp://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/相关stackoverflow问题的可能解释。

$.getJSON接受作为"成功"响应的回调函数。但如果返回了错误(404500等),则它将不会调用此函数
您需要添加额外的功能来捕捉其他响应场景:

$.getJSON( yql, cbFunc)
  .done(function() { console.log( "second success" ); })
  .fail(function(jqxhr, textStatus, error) { console.log( "error", textStatus, error ); })
  .always(function() { console.log( "complete" ); });

相关内容

  • 没有找到相关文章

最新更新