首页 > 解决方案 > injecting ajax using ScriptInjector GWT

问题描述

I want to inject ajax (to retreive data from a web service) into my html code that has been generated by GWT.

I tried injecting the cdn of jQuery and my script using ScriptInjector.

here's how I injected the cdn to the head of my html:

Element head = Document.get().getElementsByTagName("head").getItem(0);
ScriptElement sce = Document.get().createScriptElement();
sce.setSrc("http://code.jquery.com/jquery-3.1.1.min.js");
head.appendChild(sce);

that worked fine, I've inspected my page and it has been added to the head.

And here's how I tried to inject the script to get data from my web service:

ScriptInjector.fromString(" $.ajax({\n" +
"  dataType: \"json\",\n" +
"  url: \"http://localhost/geoTrackerTest.php?id=15\",\n" +
"  data: \"data\",\n" +
"  success: function(data){\n"
+"   console.log(\"success\");" +
"    document.getElementById(\"frigoTempAjax\").innerHTML = data[0].frigo_temperature;\n" +
"  }\n" +
"});").inject();

I expect to get a success message on the console and to get a value in the div that has the specified Id but I'm getting the following error:

ReferenceError: $ is not defined

标签: javascriptajaxgwt

解决方案


默认情况下,ScriptInjector将注入您的 GWT 代码运行的隐藏 iframe;您需要告诉它注入到您的页面中,而不是 jQuery 脚本所在的位置。

ScriptInjector.fromString(…).setWindow(ScriptInjector.TOP_WINDOW).inject();

但在这种情况下,最好用等效的 GWT 代码替换 jQuery 代码(使用com.google.gwt.httpor com.google.gwt.xhr


推荐阅读