2017-03-20 48 views
0

我试图在PhantomJS中使用$ .getJSON,但不可能得到它的结果。任何解决方案我不能直接加载或包含JS。页面必须从相同的域中调用。PhantomJS getJSON无法获得回应

所以我想打开一个页面,并从那里打电话。

这里是一个不工作我当前的代码:

var jqueryUrl = "https://code.jquery.com/jquery-latest.min.js"; 

page.open("http://www.example.com/", function(status) { 
    if (status === "success") { 
      page.includeJs(jqueryUrl, function() { 
      var result = page.evaluate(function() { 
       $.getJSON('http://www.example.com/someJson', function(data) { 
        return data; 
       }); 
      }); 
      console.log(result); 
      phantom.exit(); 
     }); 
    } else { 
     phantom.exit(1); 
    } 
}); 

感谢您的帮助!

+0

请加[page.onError](http://phantomjs.org/api/webpage/handler/on -error.html)处理程序来检查错误。 – Vaviloff

回答

1

你需要用组合使用page.onCallbackwindow.callPhantom,因为你正在在phantomjs上下文中的HTTP请求和结果需要请求完成后要返回只。

我没有测试的正是这种代码,但它应该是这样的:

var jqueryUrl = "https://code.jquery.com/jquery-latest.min.js"; 

page.open("http://www.example.com/", function(status) { 
    if (status === "success") { 
     page.onCallback(function(data) { 
      // got the data! 
      console.log(data); 
      phantom.exit(); 
     }); 
     page.includeJs(jqueryUrl, function() { 
      page.evaluate(function() { 
       $.getJSON('http://www.example.com/someJson', window.callPhantom); 
      }); 
     }); 
    } else { 
     phantom.exit(1); 
    } 
});