Good afternoon my friends:
I have the following code which creates a request and then uses the
request to Get data via AJAX.
How do I return the responseText to a JavaScript Object which I can access outside of the function making the request? I need to use JavaScript only, no JQuery.
The data source is formatted as JSON, here is a sample:
[{"City":"KABUL",
"Continent":"ASIA",
"Country":"AFGHANISTAN",
"CountryAbbr":"AF",
"CountryId":"102120"}]
How do I return the data to an object so that I am able to access the data for display purposes, e.g on an HTML page?
Code:
<script type="text/javascript">
function createXHR(){
if ( typeof XMLHttpRequest != 'undefined' ){
return new XMLHttpRequest();
} else if ( typeof ActiveXObject != 'undefined' ){
if (typeof arguments.callee.activeXString != 'string'){
var versions = ['MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.3.0','MSXML2.XMLHttp'], i, len;
for (i=0,len=versions.length; i < len; i++){
try {new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
} catch (ex){
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
} else {
throw new Error('No XHR object available.');
}
}
var xhr = createXHR();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
//Retrun the response text to an Object
alert(xhr.responseText);
} else {
alert('Request was unsuccessful: ' + xhr.status);
}
}
};
xhr.open('get', 'myurl/', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(null);
</script>
Finally, I attempted to populate the object like this:
var dataObject = JSON.parse(xhr.responseTex);
And access like this: For example:
console.log(dataObject[0].City);
I get the following error:
Uncaught TypeError: Cannot read property âCountryâ of undefined.
Thanks in advance.