使用 ScriptInjector GWT 注入 ajax
injecting ajax using ScriptInjector GWT
我想将 ajax(从 Web 服务检索数据)注入我的 html 代码,该代码由 GWT 生成。
我尝试使用 ScriptInjector 注入 jQuery 的 cdn 和我的脚本。
这是我如何将 cdn 注入我的 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);
效果很好,我检查了我的页面,它已添加到头部。
下面是我尝试注入脚本以从我的 Web 服务获取数据的方式:
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();
我希望在控制台上收到成功消息并在 div 中获取具有指定 ID 的值,但我收到以下错误:
ReferenceError: $ is not defined
ScriptInjector
默认情况下会注入到运行 GWT 代码的隐藏 iframe;你需要告诉它注入你的页面,而不是 jQuery 脚本所在的页面。
ScriptInjector.fromString(…).setWindow(ScriptInjector.TOP_WINDOW).inject();
但在这种情况下,最好用等效的 GWT 代码替换 jQuery 代码(使用 com.google.gwt.http
或 com.google.gwt.xhr
)
我想将 ajax(从 Web 服务检索数据)注入我的 html 代码,该代码由 GWT 生成。
我尝试使用 ScriptInjector 注入 jQuery 的 cdn 和我的脚本。
这是我如何将 cdn 注入我的 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);
效果很好,我检查了我的页面,它已添加到头部。
下面是我尝试注入脚本以从我的 Web 服务获取数据的方式:
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();
我希望在控制台上收到成功消息并在 div 中获取具有指定 ID 的值,但我收到以下错误:
ReferenceError: $ is not defined
ScriptInjector
默认情况下会注入到运行 GWT 代码的隐藏 iframe;你需要告诉它注入你的页面,而不是 jQuery 脚本所在的页面。
ScriptInjector.fromString(…).setWindow(ScriptInjector.TOP_WINDOW).inject();
但在这种情况下,最好用等效的 GWT 代码替换 jQuery 代码(使用 com.google.gwt.http
或 com.google.gwt.xhr
)