简体   繁体   中英

loading JQuery.js in my javascript

I have a js file say test.js and I want to import and use JQuery in it. I don't have a HTML file and I don't want to create one either.

I want to execute my js file once the jQuery is loaded. My code is as follows:

 var data = *some data that I am passing to the url*

function include(filename, onload) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
     script.onload = script.onreadystatechange = function() {
      if (script.readyState) {
        if (script.readyState === 'complete' || script.readyState === 'loaded') {
            script.onreadystatechange = null;                                                  
            onload();
        }
    } 
    else {
        onload();          
    }
};
head.appendChild(script);
}

 include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() {
   $(document).ready(function() {
 $.ajax({
        url: "some url,
        type: 'POST',
        crossDomain: true,
        dataType: 'json',
        data: JSON.stringify(data),
        success: function(response) {
            var data = response.hits.total;
            console.log(data);
        },
        error: function() {
          console.log("failed");
          }
       });

  });

});

This gives me an error : "ReferenceError: document is not defined"

I am running my .js file in node. How should I import and use JQuery.js to use it in my .js code?

Try using something like the request or elasticsearch modules (see npmjs.com). Node.js is different from JavaScript in the browser, so the AJAX/jquery stuff doesn't apply.

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