If语句没有使用JavaScript闭包执行

If statement is not executing with JavaScript Closures?

本文关键字:JavaScript 闭包 执行 语句 If      更新时间:2023-09-26

这是我的代码

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的URL。例如:http://phandroid.com/2015/09/25/galaxy-s7-february/

第一个方法不能得到obj.image[0].url;,因为JSON对象不存在。因为imageURL最初是一个''。因此,if条件应该执行,但它没有执行。在这种情况下,我没有收到任何街区的警报。我该怎么做呢?

试一下:

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');
      });
    }
  });

我不确定你的代码有时是如何工作的,因为当你通过$创建一个请求。getJSON,则在运行其余代码时异步获取该数据。正确的修改应该是

var url = URL;
var imageURL = '';
$.getJSON("https://graph.facebook.com?id="+encodeURIComponent(url)+"&scrape=true&method=post",
function (data) {
    parse JSON;
    imageURL = obj.image[0].url;
    alert('Facebook');
    // Do your checking of url here
    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;
        imageURL = set it here.
        alert('Yahoo');
        });
    } else {
        alert('Invalid image url');
    }
});

这样,你的雅虎块运行后,facebook块完成。