简体   繁体   English

jQuery Ajax在PhantomJS中不起作用

[英]jQuery Ajax doesn't work in PhantomJS

Whats wrong with this code? 此代码有什么问题?

I'm trying to send a post request using jQuery ajax from PhantomJS, but it returns nothing besides " post: " 我正在尝试使用PhantomJS的jQuery ajax发送发帖请求,但是除了“ 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 has two contexts. PhantomJS有两个上下文。 page.includeJs() instructs the DOM context (page context) to load the given JavaScript file. page.includeJs()指示DOM上下文(页面上下文)加载给定的JavaScript文件。 The callback is called when it is done. 完成后将调用回调。 It means jQuery will only be available in the page context and never outside of it. 这意味着jQuery仅在页面上下文中可用,而不会在页面上下文之外可用。 You get access to the page context through page.evaluate() . 您可以通过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: 您将必须使用--web-security=false命令行选项运行PhantomJS,否则由于跨域限制,它将无法发送请求:

phantomjs --web-security=false script.js

Please note that page.evaluate() is sandboxed. 请注意, page.evaluate()已沙盒化。 Please read the documentation fully. 请完整阅读文档

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: 在chrome中,可以在控制台中执行以下命令来禁用跨域限制:

chromium-browser --disable-web-security 铬浏览器-禁用Web安全

Also you can add these flags to your direct access. 您也可以将这些标志添加到直接访问中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM