我编写了这段代码,根据浏览器语言获取页面的语言文件:
$.ajax({
'async': false,
'global': false,
'url': "./languages/"+navigator.language.substring(0,2)+".json",
'dataType': "json",
'success': function (testo) {
$.each( testo, function(originalstring, newstring){
$('body').html($('body').html().replace(originalstring, newstring));
});
}
});
是否有一种简单的方法来管理“找不到文件”错误并因此加载默认语言json文件(即英语)?
答案 0 :(得分:1)
$.ajax({
'async': false,
'global': false,
'url': "./languages/"+navigator.language+".json",
'dataType': "json",
complete: function(e, xhr, settings){
if(e.status === 404){
call the same function by passing the language as english
}
},
'success': function (testo) {
$.each( testo, function(originalstring, newstring){
$('body').html($('body').html().replace(originalstring, newstring));
});
}
});
答案 1 :(得分:1)
使用ajax的错误回调
$.ajax({
async: false,
global: false,
url: "./languages/"+navigator.language+".json",
dataType: "json",
success: function (testo) {
$.each( testo, function(originalstring, newstring){
$('body').html($('body').html().replace(originalstring, newstring));
}
},
error:function( obj, textStatus, errorThrown){
//load default lang file here
}
});