简体   繁体   中英

Unable to use jQuery with server-side Rails widget

I'm creating a widget, for which I have initialized jQuery like so:

# widget.js
(function() {
  var jQuery;
  var root_url = "<%= root_url%>";

  if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.9.1') {
    var jquery_script   = document.createElement('script');
    jquery_script.type  = "text/javascript";
    jquery_script.asyc  = true;
    jquery_script.src   = "http://code.jquery.com/jquery-1.9.1.js";  

    if (jquery_script.readyState) {
      script_tag.onreadystatechange = function () { // For old versions of IE
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
          scriptLoadHandler();
        }
      };
    } else { // Other browsers
      jquery_script.onload = scriptLoadHandler;
    }

    var node = document.getElementsByTagName('script')[0];
        node.parentNode.insertBefore(jquery_script, node); 
  } else {    
    jQuery = window.jQuery;
    main(); 
  }

  function scriptLoadHandler() {
    jQuery = window.jQuery.noConflict(true);
    main(); 
  }

  function main() {
    jQuery(document).ready(function($) {
      // jQuery works great here!
      // But not so much in rendered partials or in server-side JS actions
    }
  }
})();

If I make an ajax request to my server and respond with a JS action, I can't use jQuery in my action.js.erb file. It spits out the error $ is not a function .

Similarly, even rendering partials with jQuery scripts in them yields the same results.

I think I haven't set a global instance of jQuery, and if this is the case, I'm not sure how to do that. Perhaps I'm not supposed to?

How can I get around this problem?

This solution isn't what I was looking for but I was able to combine elements of the native JS widget with an iframe. Once I manipulate whatever elements I need to on the 3rd party site (as per my widget's functionality) I render a partial housing an iframe that lets me completely control the environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM