我正在制作一个javascript网络应用,该应用会根据用户输入的内容输入有关想要从Google字体API查看的字体。我似乎无法连接到谷歌字体API。我使用他们在开发者网站上的默认代码。
https://developers.google.com/fonts/docs/developer_api
我试图在这里连接到这个JSON文件
https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyCKDRrItgVcxrwi8AZwgqMnK4hyEC5tCoY
我的AJAX代码
function getFont(fontUrl) {
var googleFontAPI = "https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyCKDRrItgVcxrwi8AZwgqMnK4hyEC5tCoY";
$.getJSON(googleFontAPI, function (data) {
var apiUrl = [];
apiUrl.push('https://fonts.googleapis.com/css?family=');
apiUrl.push(anonymousPro.family.replace(/ /g, '+'));
if (contains('italic', anonymousPro.variants)) {
apiUrl.push(':');
apiUrl.push('italic');
}
if (contains('greek', anonymousPro.subsets)) {
apiUrl.push('&subset=');
apiUrl.push('greek');
}
// url: 'https://fonts.googleapis.com/css?family=Anonymous+Pro:italic&subset=greek'
var url = apiUrl.join('');
console.log(url);
});
}
当我尝试运行代码时,它会返回此错误消息
答案 0 :(得分:1)
我认为您应该在JSON结果中搜索以查看Google字体API中是否存在字体, 然后结合变量" fontObject"的信息。 (在你的例子中称为anonymousPro)来创建字体API请求。
async function getFont(fontObject) {
var googleFontAPI = "https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyCKDRrItgVcxrwi8AZwgqMnK4hyEC5tCoY";
let url = null;
await $.getJSON(googleFontAPI, function (data) {
let result = data.items;
if(result.filter( x => x.family === fontObject.family).length > 0){
var apiUrl = [];
apiUrl.push('https://fonts.googleapis.com/css?family=');
apiUrl.push(fontObject.family.replace(/ /g, '+'));
if (fontObject.variants.includes('italic')) {
apiUrl.push(':');
apiUrl.push('italic');
}
if (fontObject.subsets.includes('greek')) {
apiUrl.push('&subset=');
apiUrl.push('greek');
}
// url: 'https://fonts.googleapis.com/css?family=Anonymous+Pro:italic&subset=greek'
url = apiUrl.join('');
}
});
console.log(url)
return url
}
let fontObject = {
family: 'Anonymous Pro',
variants: 'italic',
subsets: 'greek'
}
getFont(fontObject).then(url => {
console.log(url)
})