jQuery Ajax doesn't work in PhantomJS

2019-08-05 08:58发布

问题:

Whats wrong with this code?

I'm trying to send a post request using jQuery ajax from PhantomJS, but it returns nothing besides "post:"

var webPage = require('webpage');
var page = webPage.create();
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function() {
    console.log('post:');
    $.post("http://httpbin.org/post", function(data) {
        console.log(data);
    });
});

回答1:

PhantomJS has two contexts. page.includeJs() instructs the DOM context (page context) to load the given JavaScript file. The callback is called when it is done. It means jQuery will only be available in the page context and never outside of it. You get access to the page context through page.evaluate().

Example:

page.onConsoleMessage = function(msg){
    console.log("remote> " + msg);
};

page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function() {
    page.evaluate(function(){
        console.log('post:');
        $.post("http://httbpin.org/post", function(data) {
            console.log(data);
        });
    });
    setTimeout(function(){
        // don't forget to exit
        phantom.exit();
    }, 2000);
});

You will have to run PhantomJS with the --web-security=false commandline option, otherwise it won't be able to send the request because of cross-domain restrictions:

phantomjs --web-security=false script.js

Please note that page.evaluate() is sandboxed. Please read the documentation fully.



回答2:

The problem is related to security, you're trying to access a different domain.

In chrome it is possible to disable cross domain restrictions executing the following command in console:

chromium-browser --disable-web-security

Also you can add these flags to your direct access.