2013-12-10 65 views
3

如何將變量從服務器發送到page.evaluate?節點js + PhantomJs:將數據發送到page.evaluate

var test = 'Lorem Ipsum'; 

phantom = require('phantom') 
    phantom.create(function(ph){ 
     ph.createPage(function(page) { 
      page.open("http://www.google.com", function(status) { 
      page.evaluate(function(){ 
       $('body').html(test); 
      }); 
      page.render('google.pdf', function(){ 

      console.log('Page Rendered'); 
      ph.exit(); 
      }); 
     }); 
    }); 
}); 

非常感謝您的幫助。

EDIT1

現在它看起來像

var message = function(){ 
    return {message: 'Hello Word'}; 
}; 

phantom = require('phantom') 
    phantom.create(function(ph){ 
     ph.createPage(function(page) { 
      page.open("http://www.google.com", function(status) { 
      page.evaluate(function(content){ 
       $('body').html(content); 
      }, message); 
      page.render('google.pdf', function(){ 

      console.log('Page Rendered'); 
      ph.exit(); 
      }); 
     }); 
    }); 
}); 

現在我沒有任何錯誤,但我不知道我該怎麼處理這個對象page.evaluate

使用它

回答

1

嘗試

page.evaluate(function (...) {...}, function (err, data){...}, arg1, arg2, ...); 

例如:

var message = 'hello world'; 
page.evaluate(function(content){ 
    $('body').html(content); 
    return 'any data' 
}, function (err, anydata) {}, message); 

添加了jQuery頁面

page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function(err) { 
    //jQuery Loaded. 
    //Wait for a bit if site have AJAX 
    setTimeout(function() { 
     return page.evaluate(function() { 
      // USE JQUERY HERE 
      // 
      // 

      return 
     }, function(err, result) { 
      console.log(result); 
      ph.exit(); 
     }); 
    }, 3000); 
}); 

看到自述: https://github.com/alexscheelmeyer/node-phantom

+0

現在我在控制檯有錯誤: 幻影標準輸出:類型錯誤:「你好世界'不是一個函數(評估'cb(page.evaluate.apply(page,[fn] .concat(args)))') – form3

+0

我試着做這樣的事情 'var message = function(){ return {message:'hello world'}; };'但是現在我不知道如何處理這個對象在page.evaluate – form3

+1

中使用它啊,對不起,你正在使用phantom作爲節點(通往phantomjs的橋樑)。評估將通過回調返回結果。 – damphat

相關問題