2012-11-09 39 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

相關問題