jQuery Ajax doesn't work in PhantomJS

2019-08-05 09:00发布

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

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-05 09:19

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.

查看更多
乱世女痞
3楼-- · 2019-08-05 09:30

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.

查看更多
登录 后发表回答