Reputation: 423
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);
}
});
}
Upvotes: 0
Views: 556
Reputation: 717
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.
Upvotes: 1