سؤال

I am using JSON to display info from a site. The book example works which gave me a custom website to get information from worked, but when I replaced the url with Spider man's facebook page, it seems as if the data is processing, but the information does not display. Is there some crucial step that I am missing.

var lastReporttime = 0;
window.onload= function(){ 
  setInterval(handleRefresh,3000);
}

function updateSales(sales) {
  var salesDiv= document.getElementById("sales");
  for (var i = 0; i < sales.length; i++) {
    var sale = sales[i];
    var div = document.createElement("div");
    div.innerHTML = sale.category + sale.about + "spiderman";
    salesDiv.appendChild(div);
  }

  if (sales.length > 0) { lastReporttime = sales[sales.length-1].time; } 
}

function handleRefresh() {
  var url = "http://graph.facebook.com/SpiderManDVD"
          + "callback=updateSales"
          + "&lastreporttime=" + lastReporttime
          + "&random="+ (new Date()). getTime();

  var newScriptElement= document.createElement("script");
  newScriptElement.setAttribute("src", url);
  newScriptElement.setAttribute("id", "jsonp");

  var oldScriptElement= document.getElementById("jsonp");
  var head= document.getElementsByTagName("head")[0];
  if (oldScriptElement == null) {
    head.appendChild(newScriptElement);
  } else {
    head.replaceChild(newScriptElement, oldScriptElement);
  }
}
هل كانت مفيدة؟

المحلول

Response you received from your book example returns a JSON Array which is perfectly handled in your code.

But response from facebook api returns a JSON object which is breaking your code.

Check both the urls and update the logic inside updateSales to handle both JSON Array as well as JSONObject as per your use case.

Something like this

function updateSales(sales) {
  var salesDiv= document.getElementById('sales');

  // Check if sales is array or not (One of the crude ways, ofcourse not best but may work for you)
  if (typeof sales.length == 'undefined') {
    sales = [sales];
  }

  for (var i = 0; i < sales.length; i++) {
    var sale = sales[i];
    var div = document.createElement("div");

    div.innerHTML = sale.category + sale.about + "spiderman";
    salesDiv.appendChild(div);
  }

  if (sales.length > 0) { 
    lastReporttime = sales[sales.length-1].time; 
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top