Search code examples
phantomjsgetjson

PhantomJS getJSON unable to get a response


I'm trying to use $.getJSON inside PhantomJS but impossible to get the result of it. Any solution? I can not simply load or includeJs directly. The page has to be called from the same domain.

So I want to open a page and do the call from there.

Here is my current code which is not working:

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

Thanks for any help!


Solution

  • You need to use page.onCallback with a combination with window.callPhantom because you are making an HTTP request in phantomjs context and the result needs to be returned only after the request is done.

    I haven't tested exactly this code, but it should be something like this:

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