我有这个非常简单的代码来在发布请求后从服务器端点读取响应。实际上,我正在将数据保存到数据库并等待响应,然后再进行下一步
casper.open('http://example.com/ajax.php, {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
});
在 ajax.php 文件上,我尝试以简单的方式回显 POST 请求。 这会让我很容易知道我是否从服务器得到了正确的响应。
echo json_encode($_POST);
我尝试了这些片段,但无法得到响应。
casper.on('page.resource.received', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('http.status.200', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('resource.received', function(resp) {
this.echo(JSON.stringify(resp, null, 4));
});
最佳答案
我在向 ElasticSearch 发布查询时遇到了同样的问题,但无法检索结果。
据我所知,如果您想检索脚本回显的数据,解决方案可能是这样的:
this.echo(this.page.content);
或
this.echo(this.page.plainText);
在你的函数中。
例如(我的 ElasticSearch 案例):
/*
* SOME VAR DEFINITIONS HERE
*/
casper.start();
casper.then( function() {
// the next var is very specific to ElasticSearch
var elasticQuery = JSON.stringify (
{
'size' : 20,
'query' : {
'filtered' : {
'filter' : { 'term' : { 'locked' : false } }
}
},
'sort': { 'lastScrapeTime': { 'order': 'asc' } }
}
);
var elasticRequest = {
method: 'POST',
data: elasticQuery
}
this.thenOpen( <<YOUR URL>>, elasticRequest, function (response) {
// dump response header
require('utils').dump(response);
// echo response body
this.echo(this.page.content);
// echo response body with no tags added (useful for JSON)
this.echo(this.page.plainText);
});
}
);
casper.run();
关于phantomjs - 如何在 CasperJS 中 POST 请求后获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21705668/