LoginSignup
3
2

More than 5 years have passed since last update.

PhantomJSでAjax結果を取得する

Last updated at Posted at 2014-05-22

PhantomJSを使って、Ajaxにコールした結果を取得する方法のメモ。

通常は、直接Echoとかで確認すれば良いと思うのですが、事前にログイン処理をする必要があったり、条件が複雑だったりする場合、PhantomJSでテストできるのはありがたいところです。

(ちなみに、url = '#'にしておくと、ページ自身のソースコードを取得できます。PhantomJSには、素のHTMLソースコードを取得するメソッドが用意されていないため、これはこれで便利)

page = (require 'webpage').create()
url = '#'

page.open "http://localhost:3000/", ->
  page.evaluate (url) ->
    $.ajax url: url, success: (str) -> window.ajaxResult = str
  , url
  timer = ->
    result = page.evaluate -> window.ajaxResult
    unless result
      window.setTimeout timer, 500 # 500ms ごとにポーリングして確認
    else
      console.log result
      phantom.exit()
  timer()

もっと、きれいな書き方があるような気がしますが、oncallbackは experimental の位置づけで、今後メッセージングを主体とした方法がPhantomJSに実装される(らしい)ので、とりあえずの確実な方法として。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2