【问题标题】:casperjs does not recognize global variable stored between then statementscasperjs 无法识别存储在 then 语句之间的全局变量
【发布时间】:2018-06-23 16:57:17
【问题描述】:

所以我调用第一个 url ... 它返回一个 JSON 对象,我将 JSON 对象存储在一个名为 global_input .... 的全局变量中,然后我使用 global_input.token 打开一个链接

  var global_input = {'token' : 'xxx'} ;


    casper.start('http://localhost/client/charg/que' , function (content) {


     })
    .then(function() {
       global_input  = JSON.parse(this.getPageContent());
       casper.log( ' ==== token === > ' + global_input.token    , 'debug');

    })
    .thenOpen('http://localhost/client/charg/go/' + global_input.token , function() {

    })

    .run(function(){
        this.echo("DONE1");
        this.exit();
    });

这是日志

page init .....
[info] [phantom] Step anonymous 2/5 http://localhost/client/charg/que (HTTP 200)
[info] [phantom] Step anonymous 2/5: done in 725ms.
[info] [phantom] Step anonymous 3/5 http://localhost/client/charg/que (HTTP 200)
[debug] [phantom]  ==== token === > e608e91335fd622f430692d40e7ddf0f4b63428d
[info] [phantom] Step anonymous 3/5: done in 750ms.
[debug] [phantom] opening url: http://localhost/client/charg/go/xxx, HTTP GET

如您所见,即使日志显示 token 被设置为新值

==== token === > e608e91335fd622f430692d40e7ddf0f4b63428d

在下一步中,我仍然会得到令牌的默认值 xxx

[debug] [phantom] opening url: http://localhost/client/charg/go/xxx, HTTP GET

我错过了什么吗?

【问题讨论】:

    标签: javascript phantomjs casperjs


    【解决方案1】:

    你的 global_input 在 thenOpen 方法中注册了它的初始值。

    喜欢这个

      casper.start(static url , callback method)
            .then(callback method)
            .thenOpen(static url (here, initial global object is used) , callback method)
            .run(callback method);
    

    因此,如果您更改 static_url 中的任何内容,casperjs 将不会知道,因为它已经在 casperjs 的执行堆栈中注册了这些 url。

    你需要这样做

    var global_input = {'token' : 'xxx'} ;
    
    // this method will be called again when evaluating the url
    function getGlobalToken() {
        return global_input.token;
    }
    

    现在像这样调用get方法

    thenOpen('http://localhost/client/charg/go/' + getGlobalToken() , function() {
    
        })
    

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多