使用JavaScript从AJAX响应中获取DOM元素 [英] get DOM element from AJAX response with JavaScript

查看:926
本文介绍了使用JavaScript从AJAX响应中获取DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个AJAX请求返回一个HTML块作为一个插入到div的响应。如何使用JavaScript从AJAX响应HTML中获取DOM元素?我在返回的HTML响应div的末尾有JavaScript,但getElementById返回null,显然是因为DOM尚未创建,并且我无法像普通网页一样使用window.onload。见下面的例子。而这必须是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>


解决方案

您有两个选项,具体取决于您需要哪些浏览器支持:


  1. 如果您需要支持所有浏览器,请将您的 console.log 代码进入ajax响应后调用的成功函数。这将确保只有在通过ajax更新div之后才能运行。


  2. 如果您只需要支持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:

  1. 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.

  2. If you only need to support HTML5-compatible browsers, listen to the DOMNodeInserted event on the "name" div and instead of changing it via innerHTML, create and append the html code objects

这篇关于使用JavaScript从AJAX响应中获取DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆