Here is my test.json file
{
"pageTitle": "Test Page",
"firstName": "Matt"
}
Here is how I'm accessing it in my JS file
var jsonObj = {};
var ajaxReq = new XMLHttpRequest();
ajaxReq.overrideMimeType("application/json");
ajaxReq.open('GET', 'path/to/file/test.json', true);
ajaxReq.onreadystatechange = function ()
{
if (ajaxReq.readyState == 4)
{
jsonObj = ajaxReq.responseText;
alert(jsonObj.pageTitle);
}
}
ajaxReq.send(null);
But when I run the script the alert box says 'undefined'. Can anyone please tell me what I'm doing wrong here? I've been working at this for a couple hours now and can't seem to find the answer. Thank you for any help.
The responseText
property refers to a string, containing the response text. It doesn't contain a JavaScript object, and therefore doesn't have a pageTitle
property.
Since the string is in the JSON format, it can be easily parsed into an object with the JSON.parse
method:
jsonObj = JSON.parse(ajaxReq.responseText);
update jsonObj = ajaxReq.responseText;
to follow line,please try!
jsonObj = eval('(' + ajaxReq.responseText + ')');
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.