How would you access variable values from scripts tags in HTML source of a page fetched via xhr request.
HTML of fetched page...
<html>
<body>
<div id="somecontent"></div>
<script>
var foo="30";
</script>
<script>
var bar="60";
</script>
</body>
</html>
And fetched via xhr request...
var xhr = new XMLHttpRequest();
xhr.open("GET","http://www.example.com/testpage.html");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var html = xhr.responseText;
// try to access var
var result =html.foo+html.bar;
console.log(result);
}
}
xhr.send();
Any ideas would be greatly appreciated!
You can try something like that:
var xhr = new XMLHttpRequest();
xhr.open("GET","http://www.example.com/testpage.html");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var html = xhr.responseText;
var parser = new DOMParser();
var dom = parser.parseFromString(html, 'text/html');
var scripts = dom.querySelectorAll('script');
for (let script of scripts) {
eval(script.innerText);
}
console.log('foo', foo);
console.log('bar', bar);
}
}
xhr.send();
I have data on a website which looks like this
[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]
I have a html file with javascript code as follows:
function httpGet(url) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
var data = xmlHttp.responseText;
data = (JSON.parse(data));
I need to access the "name" attribute from the URL database and form a string concat of all the name attributes. Could you please help me out what to be done next?
Below is my test data
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name);
For Example if you want to acces the name you can access as like above.
To concatenate the vales do like below
var Output = json.map(function(result) {
return result.name;
}).join('');
alert(Output);
Have a look on it https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var result = data.map(function(user) {
return user.name;
}).join('');
<html>
<head>
<script type="text/javascript">
function fun(){
var str='[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]';
var obj=eval(str);
var names='';
for(var item in obj){
names+=obj[item].name;
}
alert(names);
}
</script>
</head>
<body>
<input type="button" onclick="fun()" value="click me"/>
</body>
</html>
I got what you mean.It is the Ajax problem.If you really use the code that you provided,it should not work.Here is the Ajax code to get response from a certain url:
var ajaxRequest;
//create ajax object
function createAjaxRequest() {
var xmlhttp = null;
if (window.XMLHttpRequest) {// code for all new browsers
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {// code for IE5 and IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
//send request and identify callbak handler
function send(url) {
ajaxRequest = createAjaxRequest();
ajaxRequest.onreadystatechange = callback;
ajaxRequest.open("POST", url, true);
ajaxRequest.send(null);
}
// the callback handler
function callback() {
if (ajaxRequest.readyState == 4) {// 4 = "loaded"
if (ajaxRequest.status == 200) {// 200 = OK
var data = ajaxRequest.responseText;
}
else {
alert("Problem retrieving data");
}
}
}
I am trying to create a simple XML node with text "New node!"
var xmlDoc = loadXMLDoc("myFile.xml");
var newElem = xmlDoc.createElement("elem");
newElem.innerHTML = "New node!";
Where loadXMLDoc() is
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname, false);
xhttp.send();
return xhttp.responseXML;
}
But the code does not work. I expect the XML file to have a new node "<elem>" with "New node!" in it, but it was still the same. I have no idea why. There were no error messages.
How do I get my code to work?
Your code is creating a new element, but you are not appending it to the XML.
See the example here: https://developer.mozilla.org/en-US/docs/Web/API/document.createElement#Example
i have an RegistrationResponseMessages.xml:
<messages>
<error>
<code id="501">Couldn't retrieve the HTML document because of server-configuration problems.</code>
<code id="502">Server busy, site may have moved ,or you lost your dial-up Internet connection.</code>
</error>
<success></success>
</messages>
trying to read contents of code id 501 and 502 with javascript, but it not works.
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "RegistrationResponseMessages.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById("errorCode403").innerHTML = getElementsByTagName(501)[0].childNodes[0].nodeValue);
displaying it here:
<label id="errorCode403" style="font-weight: 600; color: red;">give some error</label>
what is my problem?
It's ajax, you have to wait for the data to be returned, then you have to access it the right way:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onload = function() {
var xmlDoc = this.responseXML,
value = xmlDoc.getElementsByTagName('501')[0].childNodes[0].nodeValue;
document.getElementById("errorCode403").innerHTML = value;
}
xmlhttp.open("GET", "RegistrationResponseMessages.xml", false);
xmlhttp.send();
Not sure about the traversal in the XML, as 501 sounds like a strange tagName ?
EDIT:
to get a list of the ID's you do this inside the onload handler:
xmlhttp.onload = function() {
var xmlDoc = this.responseXML,
var codes = xmlDoc.getElementsByTagName('code');
var array = [];
for (var i=0; i<codes.length; i++) {
array.push( codes[i].id );
}
console.log(array);
}
I have 2 .jsp pages.
The 1. one contains just a xml structure for applicants:
<% response.setContentType("text/xml") ; %>
<applicant>
<citizenship>GERMANY</citizenship>
<residence>Inc.</residence>
<street>9500 Gilman Drive</street>
<city>La Jolla</city>
<state>USA</state>
<countryTelCode>Vandelay Industries</countryTelCode>
<zipCode>Inc.</zipCode>
<areaCode>9500 Gilman Drive</areaCode>
<telNumber>La Jolla</telNumber>
<major>USA</major>
<awarded>Vandelay Industries</awardeds>
<gpa>Inc.</gpa>
<specialization>9500 Gilman Drive</specialization>
</applicant>
The second one tries to retrieve GERMANY from the tag and print it in the "..." field of:
<span id="Citizenship">...</span>
using this code after calling showCustomer():
<script type="text/javascript">
function showCustomer() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "getApplicant_xml.jsp";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var xmlDoc = xmlHttp.responseXML.documentElement;
document.getElementById("Citizenship").innerHTML = xmlDoc.getElementsByTagName("citizenship")[0].childNodes[0].nodeValue;
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
}
</script>
Unfortunately it does not print anything....
I would be really thankful if someone finds my mistake.
Thank you
Your problem is that xmlHttp.responseXML is null. You need to parse a new DOM object from xmlHttp.responseText. I fixed the code.
<script type="text/javascript">
function showCustomer() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "getApplicant_xml.jsp";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var xmlDoc = xmlHttp.responseText;
xmldom = (new DOMParser()).parseFromString(xmlDoc, 'text/xml');
text = xmldom.getElementsByTagName("citizenship")[0];
document.getElementById("Citizenship").innerHTML = text.childNodes[0].nodeValue;
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
};
</script>