0

I am getting following exception: jdk.nashorn.internal.runtime.ECMAException: ReferenceError: "$" is not defined

But how can I have jquery available for the javascript function?

Following is my code: Java code:

@RequestMapping(value={"/callAjax"}, method={RequestMethod.POST, RequestMethod.GET})
    public String callAjax(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        logger.info("request came to /callAjax");

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        InputStream fis = AjaxRequestController.class.getResourceAsStream("path to my js file");
        InputStreamReader fileReader = new InputStreamReader(fis);
        engine.eval(fileReader);
        Invocable inv = (Invocable) engine;
        inv.invokeFunction("ajaxMethod");
        return null;
    }

Javascript:

function ajaxMethod(){
    $.ajax({ 
        dataType: "json",
           type: "GET", 
           cache: false,
           url: 'myurl',
           success: function (data) {
            console.log(data);
        }
    });
}

1 Answer 1

1

In short, you can't!

Although nashorn (java 8's javascript engine) runs ECMAscript compliant javascript, but implicit objects from browsers like window, document are still not available. JQuery or $, attaches it to window object hence it will not work. Use other ways for making async http requests in java.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.