【问题标题】:Getting nothing when doing cross domain AJAX request with YQL使用 YQL 进行跨域 AJAX 请求时一无所获
【发布时间】:2013-06-23 18:44:55
【问题描述】:

我正在使用以下代码执行 使用 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) {
alert(results);
});

当我在 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 问题中的可能解释。

【问题讨论】:

    标签: javascript ajax jquery cross-domain yql


    【解决方案1】:

    $.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" ); });
    

    【讨论】:

    • 它在控制台中显示“错误”和“完成”。你能解释一下为什么吗?
    • 这意味着响应没有返回带有 200 代码的成功标头,而是返回了其他内容。我已经修改了上面的答案,现在在回调中包含您可以检查的其他字段。
    • 表示响应中的数据不是有效的 JSON。使用 chrome 打开开发工具,然后导航到“网络”选项卡,然后执行您的 AJAX 请求,并在下面的列表中找到该请求。选择它并转到“响应”部分 - 可能不是有效的 JSON,甚至完全不是其他的。使用开发工具来验证这些东西。
    • 在响应选项卡中有 cbFunc(),其中包含所有请求的“json”格式数据。使用萤火虫显示“json解析错误”。所以这是否意味着结果取决于服务器发送的数据(即json错误是由于服务器错误的json)或其他任何事情。请清除这个......
    • 这意味着服务器发送了无效的 JSON 数据或者可能根本没有 JSON。在 chrome Dev Tools 中有 Network 选项卡,请查看来自服务器的响应,如果是 JSON,请使用此服务进行验证:jsonlint.com 它会在 JSON 中显示错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多