jQuery Ajax doesn't work in PhantomJS

送分小仙女□ 提交于 2019-12-13 17:07:42

问题


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.



来源:https://stackoverflow.com/questions/31431153/jquery-ajax-doesnt-work-in-phantomjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!