使用JavaScript从AJAX响应中获取DOM元素 [英] get DOM element from AJAX response with JavaScript
问题描述
< div class =page-content extractAjaxContentid =tableContent_AJAX>
< div id =name> Biff< / div>
< html:form action =/ variableCostStatusPostmethod =post>
....一些JSP生成HTML
< / html:form>
< script> console.log(Name is+ document.getElementById('name'));< / script>
< / div>
您有两个选项,具体取决于您需要哪些浏览器支持:
-
如果您需要支持所有浏览器,请将您的
console.log
代码进入ajax响应后调用的成功函数。这将确保只有在通过ajax更新div之后才能运行。 -
如果您只需要支持HTML5兼容的浏览器,请听
DOMNodeInserted
事件在namediv上,而不是通过innerHTML
更改它,创建并附加html代码对象
I have an AJAX request that returns a chunk of HTML as a response that is inserted into a div. How can I use JavaScript to get an element of DOM from that AJAX response HTML? I have JavaScript at the end of the returned HTML response div, but getElementById returns null, apparently because the DOM hasn't been created, and I can't use window.onload like on a normal web page. See eample below. And this has to be in JavaScript - no libraries.
<div class="page-content extractAjaxContent" id="tableContent_AJAX">
<div id="name">Biff</div>
<html:form action="/variableCostStatusPost" method="post">
....some JSP to produce HTML
</html:form>
<script>console.log("Name is " + document.getElementById('name'));</script>
</div>
You have two options, depending on which browsers you need to support:
If you need to support all browsers, put your
console.log
code into the "success" function that's called after the ajax response. This will ensure it runs only after the div is updated by ajax.If you only need to support HTML5-compatible browsers, listen to the
DOMNodeInserted
event on the "name" div and instead of changing it viainnerHTML
, create and append the html code objects
这篇关于使用JavaScript从AJAX响应中获取DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!