Ajax response as DOM object

大兔子大兔子 提交于 2019-12-02 04:41:20

问题


Is there a way to get a response from the typical ajax function so that it can be dissected with getElements? I've tried query.responseText.getElementById but it works just as bad as it looks. You should be able to tell what I'm trying to achieve by seeing that snippet, though. I just need to get elements from an ajax response the same way as I would a normal DOM object.

Also, please do not suggest using jQuery. I use it when I have a lot of script and can use a lot of its functions, but in this case I only have a short script and a library 70x the size of it would seem like a waste.


回答1:


Well you could have a hidden div on your page and set it's innerHTML to the Ajax response you receive. You could then call div.getElementById(), since it is then just another DOM object.




回答2:


Refer to this article: Parsing XML response in Ajax

In this case I am using responseXML. You can make use of getElementsByTagName and other getElement*() methods to get your data.




回答3:


Parsing an SVG or HTML document

parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html");

doc will be a valid html document.




回答4:


If your response is TEXT, I've seen ppl use ...xhr.responseText.spit('html>...body>...div id="yourTargetsParent">')[1].split('/div>.../body>.../html>')[0]; //just split the string up however!

Another way is to use iframe.contentWindow.document.body... (or contentDocument for some browsers)... just hide the iframe ya know.

Obviously, if you have control over the target that totally changes things (and this post probably wouldn't be here), but I've also seen some mean work arounds with the target's use of scripting its host dom, localStorage, splits/joins, webSQLDatabases, ...for string manipulation.

Honestly, I used to use a hidden div(thank you asleepysamurai!), but I thought I came across a more getElementById/jQuery.load type way. ..I'll post back if I find it...



来源:https://stackoverflow.com/questions/5447928/ajax-response-as-dom-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!