JSON请求超时或结果不一致

时间:2013-05-26 06:14:42

标签: json callback yql

我正在使用JSON和YQL访问外部域中的一些数据。

http://jsfiddle.net/NdkPU/22/

但我遇到的问题是代码只能间歇性地工作,有时我得到一个回复​​,有时候什么也没有。

显然这是访问这些数据的一个非常缓慢的解决方案 - 所以我认为可能是超时或回调函数存在问题的一个原因。

为什么结果不能一直工作的任何想法?

// Start function when DOM has completely loaded 
    $(document).ready(function(){ 

  requestCrossDomain("http://api.fool.com/caps/ws/Ticker/GOOG/Pitches/10?apikey=rW3550aXdsuJPg4bKEemC13x39jDNR6f", function (result) {
    var num = 1;

    var browserName = navigator.appName;
    var doc;
    if (browserName == 'Microsoft Internet Explorer') {
        doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.async = 'false'
        doc.loadXML(result.results);
    } else {
        doc = (new DOMParser()).parseFromString(result.results, 'text/xml');
    }
    var xml = doc;

    console.log("Data Loaded: " + xml);
// Build an HTML string
myHTMLOutput = '';
 myHTMLOutput += '<table width="98%" border="1" cellpadding="0" cellspacing="0">';
  myHTMLOutput += '<th>Text</th>';

// Run the function for each student tag in the XML file
$('Pitch',xml).each(function(i) {
  PitchText = $(this).find("Text").text(); 

  // Build row HTML data and store in string
  mydata = BuildStudentHTML(PitchText);
  myHTMLOutput = myHTMLOutput + mydata;
});
myHTMLOutput += '</table>';

myHTMLOutput += '<br>Rating: ';

myHTMLOutput += $('Ticker',xml).attr("Percentile");

// Update the DIV called Content Area with the HTML string
$("#ContentArea").append(myHTMLOutput);
  });
});



 function BuildStudentHTML(PitchText){

  // Build HTML string and return
  output = '';
  output += '<tr>';
  output += '<td>'+ PitchText + '</td>';
  output += '</tr>';
  return output;
}


// Accepts a url and a callback function to run.
function requestCrossDomain(site, callback) {

// 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 xml where url="' + site + '"') + '&format=xml&callback=?';

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

 function cbFunc(data) {
    // If we have something to work with...
    if (data.results[0]) {
        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.');
}
}

1 个答案:

答案 0 :(得分:0)

看起来它只是一个缓慢的API。我写了一个简单的bash循环,使用curl计时查询,这里是时间:

 7.4 sec
11.1 sec
11.2 sec
 7.4 sec
11.1 sec
 7.3 sec
10.2 sec
11.8 sec
11.3 sec
 7.1 sec