PhantomJS getJSON 无法得到响应
PhantomJS getJSON unable to get a response
我正在尝试在 PhantomJS 中使用 $.getJSON 但无法获得结果。任何解决方案?我不能简单地直接加载或 includeJs。该页面必须从同一域调用。
所以我想打开一个页面并从那里拨打电话。
这是我当前无法运行的代码:
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);
}
});
感谢您的帮助!
您需要将page.onCallback
与window.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);
}
});
我正在尝试在 PhantomJS 中使用 $.getJSON 但无法获得结果。任何解决方案?我不能简单地直接加载或 includeJs。该页面必须从同一域调用。
所以我想打开一个页面并从那里拨打电话。
这是我当前无法运行的代码:
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);
}
});
感谢您的帮助!
您需要将page.onCallback
与window.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);
}
});