jQuery Ajax在PhantomJS中不起作用 [英] jQuery Ajax doesn't work in PhantomJS

查看:229
本文介绍了jQuery Ajax在PhantomJS中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码有什么问题?

我正在尝试使用PhantomJS的jQuery ajax发送发帖请求,但是除了" post:"

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

推荐答案

PhantomJS具有两个上下文. page.includeJs()指示DOM上下文(页面上下文)加载给定的JavaScript文件.回调完成后将被调用.这意味着jQuery仅在页面上下文中可用,而不会在页面上下文之外可用.您可以通过page.evaluate()访问页面上下文.

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().

示例:

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

您必须使用--web-security=false命令行选项运行PhantomJS,否则由于跨域限制,它将无法发送请求:

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

请注意,page.evaluate()已沙盒化.请完整阅读文档.

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

这篇关于jQuery Ajax在PhantomJS中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆