如果语句没有使用JavaScript闭包执行?

时间:2015-10-10 17:53:12

标签: javascript json facebook-graph-api

这是我的代码

var url = URL;
var imageURL = '';

$.getJSON("https://graph.facebook.com/?id="+encodeURIComponent(url)+"&scrape=true&method=post",
  function (data) {
    json_data = JSON.stringify(data); 
    json_data = json_data.replace(/\s+/g, ' '); 
    var obj = jQuery.parseJSON(json_data);
    imageURL = obj.image[0].url;
    alert(imageURL+'Facebook');

    if(imageURL == ''){
      $.getJSON("//query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20WHERE%20url=%27"+encodeURIComponent(url)+"%27%20AND%20xpath=%27descendant-or-self::meta%27&format=json&callback=?"
      , function(data) {
          var res = $.grep(data.query.results.meta, function(image, key) {
          return image.hasOwnProperty("property") && image.property === "og:image"
        });
       if (res.length > 0) {
         var imageURL = res[0].content;
         alert(imageURL+'Pinterest');
      });
    }
});

现在,大部分时间都有效。但在某些情况下,例如Phandroid的任何网址。例如,http://phandroid.com/2015/09/25/galaxy-s7-february/

第一种方法无法获取obj.image[0].url;,因为JSON对象不存在。因为,imageURL最初是''。因此,if条件应该执行,但它不会。在这种情况下,我不会收到来自任何区块的警报。我该怎么办?

2 个答案:

答案 0 :(得分:0)

试试这样:

var url = URL;
var imageURL = '';

$.getJSON("https://graph.facebook.com/?id="+encodeURIComponent(url)+"&scrape=true&method=post",
  function (data) {
    // parse JSON; // <-- you have to correct this
    imageURL = obj.image[0].url;
    alert('Facebook');


    if(imageURL == ''){
      $.getJSON("//query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20WHERE%20url=%27"+encodeURIComponent(url)+"%27%20AND%20xpath=%27descendant-or-self::meta%27&format=json&callback=?"
    , function(data) {
        // parse JSON; // <-- you have to correct this
        imageURL = 'set it here.'// <-- you have to correct this
        alert('Yahoo');
      });
    }

  });

答案 1 :(得分:0)

我不确定您的代码有时是如何工作的,因为当您通过$ .getJSON创建请求时,它会在其余代码运行时异步提取该数据。一个适当的解决方案是

match.Date = dt;

这样,你的Yahoo块就会在facebook块完成后运行。