首先看一下这个函数,注意json文件位于本地:
if (request) {
request.open("GET", "flicks.json", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var testi = request.responseText;
var listmovies = JSON.parse(testi);
console.log(typeof testi); // THIS RETURNS STRING
console.log(typeof listmovies); // THIS RETURNS OBJECT - YAY!
}
};
request.send(null);
}
这很完美,我得到了我想要的东西,一个包含JSON数据的对象。
但是当我更改JSON文件的位置并将其放在服务器上时:
request.open("GET", "http://www.myserver.com/flicks.json", true);
然后它回来了这个错误:
SyntaxError: JSON.parse: unexpected end of data
示例JSON
{
"feed": "....",
"description": "Fake List of Netflix movies",
"modified": "2010-10-25T15:04:46Z",
"generator": "I did it",
"items": [
{
"title": "...",
"link": "h...",
"media": {
"m": "..."
},
"date_taken": "..."
},
{
"title": "...",
"link": "...",
"media": {
"m": "..."
},
"date_taken": "..."
}
]
}
为什么它在本地工作而不是其他方式?
答案 0 :(得分:0)
如果您在浏览器中添加:http://www.myserver.com/flicks.json
,您能看到数据吗? (文件是否可访问)。第二个猜测,你确定文件是相同的(本地与服务器)?
编辑1: 试试这个。只是电话顺序略有变化。
if (request) {
request.onreadystatechange = function() {
if (request.readyState == 4) {
var testi = request.responseText;
var listmovies = JSON.parse(testi);
console.log(typeof testi); // THIS RETURNS STRING
console.log(typeof listmovies); // THIS RETURNS OBJECT - YAY!
}
};
request.open("GET", "http://www.myserver.com/flicks.json", true);
request.send(null);
}