javascript - 使用YQL进行跨域AJAX请求时什么也没得到

标签 javascript ajax jquery cross-domain yql

我使用以下代码来执行使用 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[^>]*>[\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");

}

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

当我在 Firefox 中运行上述代码时,虽然响应(在 Firebug 控制台中)显示回调函数(cbFunc)内的网站内容,但它没有显示任何警报。
还有 console.log("inside call back") 的结果第 5 行未在 Firebug 控制台中打印。

任何人都可以建议我哪里出了问题或者对上述问题有任何解释吗?
顺便说一句,我已经经历过:
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/ 相关 stackoverflow 问题中可能的解释。

最佳答案

$.getJSON接受作为“成功”响应的回调函数。但如果返回错误(404、500 等),则不会调用此函数。
您需要添加额外的函数才能捕获其他响应场景:

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

关于javascript - 使用YQL进行跨域AJAX请求时什么也没得到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17323272/

相关文章:

javascript - 如何在不刷新页面的情况下每分钟自动更新股票价格?

javascript - D3 中的过滤选项

javascript - Bootstrap Carousel 不工作(一次显示所有图像)

javascript - 在javascript中访问对象内数组内的对象

javascript - 有没有办法为每个 AJAX 页面加载初始化 JS SDK?

Jquery:向已选择的对象添加选择器

jquery - 加载多个图像后按顺序淡入它们

javascript - 如何在javascript中实现环回CURL?

javascript - IE9和IE9 Compatibility View浏览器模式的区别

javascript - 没有JQUERY的使用AJAX发送表单数据的POST方法