Dan*_*ves 5 javascript ajax jquery getjson http-status-code-404
我正在尝试使用该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();
Run Code Online (Sandbox Code Playgroud)
从控制台日志中我可以看到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();
Run Code Online (Sandbox Code Playgroud)
在此之后,我的控制台向我提供了以下信息:
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]
Run Code Online (Sandbox Code Playgroud)
我确保JSON提要的标头是最新的,并且提要肯定提供有效的JSON(它有效地缓存第三方服务提要以节省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]
Run Code Online (Sandbox Code Playgroud)
是因为你的JSON无效.即使响应从服务器正确返回,如果您的dataType是'json'并且返回的响应没有正确格式化JSON,jQuery将执行error函数参数.
http://jsonlint.com是一种非常快速简便的方法来验证JSON字符串的有效性.
| 归档时间: |
|
| 查看次数: |
16713 次 |
| 最近记录: |