[英]Issue with accessing JSON file?
Here is my test.json file 这是我的test.json文件
{
"pageTitle": "Test Page",
"firstName": "Matt"
}
Here is how I'm accessing it in my JS file 以下是我在JS文件中访问它的方法
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. responseText
属性引用包含响应文本的字符串。 It doesn't contain a JavaScript object, and therefore doesn't have a pageTitle
property. 它不包含JavaScript对象,因此没有
pageTitle
属性。
Since the string is in the JSON format, it can be easily parsed into an object with the JSON.parse
method: 由于字符串采用JSON格式,因此可以使用
JSON.parse
方法将其轻松解析为对象:
jsonObj = JSON.parse(ajaxReq.responseText);
update jsonObj = ajaxReq.responseText;
update
jsonObj = ajaxReq.responseText;
to follow line,please try! 请关注,请尝试!
jsonObj = eval('(' + ajaxReq.responseText + ')');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.