2012-11-09 43 views
6

在执行CasperJS脚本的过程中,我需要从另一个站点获取和解析JSON数据,以便我可以使用该数据在网站上填写表单积极努力。在CasperJS中使用AJAX获取页面的远程数据

我该怎么做?

+0

通过使用xmlhttprequest? – NiKo

+0

这就是我如何使用jQuery。不知道用CasperJS做这件事的最佳方法。请记住,这是一个跨域请求,我不认为这是casper内的问题。 – eComEvo

回答

8

您可以使用__utils__.sendAJAX()

var casper = require('casper').create(); 
var wsurl = 'https://raw.github.com/n1k0/casperjs/master/package.json'; 
var word; 

casper.start('http://google.com/', function() { 
    word = this.evaluate(function(wsurl) { 
     try { 
      return JSON.parse(__utils__.sendAJAX(wsurl, 'GET', null, false)).name; 
     } catch (e) { 
     } 
    }, {wsurl: wsurl}); 
}); 

casper.then(function() { 
    if (!word) { 
     this.die('unable to retrieve word'); 
    } 
    this.echo('searching for ' + word); 
    this.fill('form[action="/search"]', {q: word}, true); 
}); 

casper.run(function() { 
    this.echo(this.getCurrentUrl()); 
    this.exit(); 
}); 

样品执行(不要忘记通过--web-security=no):

$ casperjs test.js --web-security=no 
searching for casperjs 
http://www.google.fr/search?hl=fr&source=hp&q=casperjs&gbv=2&oq=&gs_l= 

希望它能帮助。

+0

完美!谢谢! :) – eComEvo

+0

@NiKo如果我想编辑ajax请求的http头,该怎么办?我看到有一个[讨论](https://groups.google.com/forum/#!msg/phantomjs/z9WVs0SwiwM/eHifuw5RJNIJ)关于在phantomjs中添加它,但我不知道它是否有任何地方..建议? – abbood

+0

@NiKo我猜这是不可能[尚](https://github.com/ariya/phantomjs/issues/10745) – abbood

相关问题