mrb mrb - 1 year ago 144
JSON Question

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(;):

<SCRIPT language='JavaScript1.1' SRC=";sz=300x250;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=?"></SCRIPT><NOSCRIPT><A HREF=";sz=300x250;ord=[timestamp]?"><IMG SRC=";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!

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download