问题
I want to run jQuery in a Ruby application and use it to manipulate an HTML string. (Yes, I know there are other Ruby libraries that can handle that task, but I have a good reason for using jQuery in this case.) Is this possible? I know that I can use ExecJS to execute simple JavaScript code in my Ruby application, but jQuery doesn't seem to be working:
irb(main):001:0> require 'execjs'
=> true
irb(main):002:0> require 'open-uri'
=> true
irb(main):003:0> context = ExecJS.compile(open("http://code.jquery.com/jquery-1.9.1.js").read)
=> <Return omitted for brevity>
irb(main):004:0> context.call("$", "<div>Test</div>")
ExecJS::ProgramError: ReferenceError: window is not defined
from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-1.4.0/lib/execjs/external_runtime.rb:68:in `extract_result'
from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-1.4.0/lib/execjs/external_runtime.rb:28:in `block in exec'
from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-.4.0/lib/execjs/external_runtime.rb:41:in `compile_to_tempfile'
from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-.4.0/lib/execjs/external_runtime.rb:27:in `exec'
from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-.4.0/lib/execjs/external_runtime.rb:19:in `eval'
from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-.4.0/lib/execjs/external_runtime.rb:33:in `call'
from (irb):4
from c:/RailsInstaller/Ruby1.9.3/bin/irb:12:in `<main>'
How do I get this to work?
回答1:
The error message tells you what the problem is:
ExecJS::ProgramError: ReferenceError: window is not defined
jQuery is a library for DOM manipulation. It expects to see all of the usual DOM objects and interfaces, including the window
object.
The ExecJS library you're using doesn't provide a DOM or a window
object. It provides a JavaScript execution context, but not the same one a browser provides.
You may possibly be able to get this working by using another library such as JSDOM to provide a DOM that jQuery can use. Here is a search that may give some tips.
The first link describes a use of JSDOM and jQuery with ExecJS that may be similar to what you want.
That said, why jQuery? There are several good Ruby HTML parsers including Nokogiri. Why not try one of those?
回答2:
You can't run jQuery in Ruby. jQuery isn't written in Ruby, it's in JavaScript so you'll need to run a JavaScript interpreter to use it.
来源:https://stackoverflow.com/questions/15423454/running-jquery-in-ruby