简体   繁体   中英

How to get element value from JSON object and first convert it to HTML and then to String

Hi i´m getting a JSON string from an XMLHttpRequest which I fist convert into a JavaScript Object:

response = JSON.parse(xmlhttp.responseText);

One of the JSON element values is a string which represents a script tag with a noscript tag like that (output shows console.log(response.ad.con);):

<SCRIPT language='JavaScript1.1' SRC="https://ad.doubleclick.net/ddm/adj/N378.150781.4704472308521/B5632202.128522416;sz=300x250;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=?"></SCRIPT><NOSCRIPT><A HREF="https://ad.doubleclick.net/ddm/jump/N378.150781.4704472308521/B5632202.128522416;sz=300x250;ord=[timestamp]?"><IMG SRC="https://ad.doubleclick.net/ddm/ad/N378.150781.4704472308521/B5632202.128522416;sz=300x250;ord=timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=?" BORDER=0 WIDTH=300 HEIGHT=250 ALT="Advertisement"></A></NOSCRIPT>

I now wanna get the string which is in the SRC element of the script tag. How can I do that? I think i´m lost in conversion...

Thanks a lot!

You can use DOMParser to parse HTML strings, just like you would JSON etc. and then just get the attribute with DOM methods

var response = JSON.parse(xmlhttp.responseText);

var parser   = new DOMParser();
var doc      = parser.parseFromString(response.propertyWithHtml, "text/html");

var src      = doc.querySelector('script').getAttribute('src');

如果您使用jQuery,请尝试

$('<SCRIPT language="JavaScript1.1" SRC="https://ad.doubleclick.net/ddm/adj/N378.150781.4704472308521/B5632202.128522416;sz=300x250;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=?"></SCRIPT><NOSCRIPT><A HREF="https://ad.doubleclick.net/ddm/jump/N378.150781.4704472308521/B5632202.128522416;sz=300x250;ord=[timestamp]?"><IMG SRC="https://ad.doubleclick.net/ddm/ad/N378.150781.4704472308521/B5632202.128522416;sz=300x250;ord=timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=?" BORDER=0 WIDTH=300 HEIGHT=250 ALT="Advertisement"></A></NOSCRIPT>').attr("SRC")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM