【发布时间】:2013-01-03 09:23:51
【问题描述】:
我正在尝试使用getJSON 方法获取我用jQuery 编写的自定义JSON 提要。由于未知原因,该 URL 似乎已从末尾剥离 cache_gen.php?location=PL4 并替换为 [object%20Object] 导致发生 404 错误。
这是我正在使用的 jQuery:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
从控制台日志我可以看到 URL 字符串正确计算为:http://weatherapp.dev/cache_gen.php?location=PL4
但是控制台中的第二行是:Failed to load resource: the server responded with a status of 404 (Not Found)。
谁能指出我正确的方向?
更新 19/01/2013 23:15
好吧,我刚刚进行了转换,因此使用$.ajax 完全适合文档。我还添加了一个失败事件并记录了传递给它的所有数据。
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
在此之后,我的控制台会为我提供以下信息:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
我已确保 JSON 提要的标头是最新的,并且提要肯定提供有效的 JSON(它有效地缓存了第 3 方服务提要以节省 API 成本)。
【问题讨论】:
-
@popnoodles,它可能是
/etc/hosts重定向:)。但是,当然.dev听起来很可疑 -
.dev 是一个开发域。它已经在我的本地系统上设置了一个 Apache 虚拟主机,它在我的
/etc/hosts中有一个条目,以确保正确解析。我可以在浏览器中访问此域,它与加载 JS 文件的域相同。 -
当您浏览到 URL 时屏幕上会出现什么?
-
我可以证明这一点,从开发工具复制您的回复并将其粘贴到 jsonlint.com - 它会告诉您您的错误在哪里。
标签: javascript jquery ajax http-status-code-404 getjson