我正在尝试使用 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
但是控制台中的第二行是:无法加载资源:服务器响应状态为 404(未找到)
。
谁能用这个给我指出正确的方向?
更新时间 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 提要的 header 是最新的,并且该提要肯定提供有效的 JSON(它有效地缓存了第 3 方服务提要以节省 API 成本)。
最佳答案
您看到此错误的原因:
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' 并且返回的响应不是格式正确的 JSON,jQuery 将执行错误函数参数。
http://jsonlint.com是验证 JSON 字符串有效性的一种非常快速和简单的方法。
关于javascript - jQuery 中附加 [object%20Object] 的 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419730/