javascript - 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
解决方案
默认情况下,ScriptInjector
将注入您的 GWT 代码运行的隐藏 iframe;您需要告诉它注入到您的页面中,而不是 jQuery 脚本所在的位置。
ScriptInjector.fromString(…).setWindow(ScriptInjector.TOP_WINDOW).inject();
但在这种情况下,最好用等效的 GWT 代码替换 jQuery 代码(使用com.google.gwt.http
or com.google.gwt.xhr
)
推荐阅读
- reverse-engineering - DBI Frida Stalker 不跟踪指令
- javascript - Express.js - 待处理的承诺阻止并延迟 express 中的下一个 GET 请求(Node.js)
- gsap - 当移动响应视图设置为触摸模拟和在实际移动设备上时,Bulma 和 scrollTrigger 更改/中断
- python - 在 Plotly 的图例中对每个“图形维度”进行分组
- visual-studio-code - VScode:设备同步
- c++ - 整数计数{0}。我可以在 C++ 中使用花括号初始化变量吗?
- reactjs - 如何在reactjs中禁用eslint检查开发模式
- kotlin - IntelliJ 新 JavaFX 项目剂量工作 - InvalidModuleDescriptorException
- c# - 如果我按右 alt 这个隐藏,当我再次按程序显示和隐藏时
- gcc - 如何在 GCC 中启用所有 Intel Intrinsic 选项?