$.getJSON and google fonts API stops working in internet explorer with jQuery versions greater than 1.4.4

╄→尐↘猪︶ㄣ 提交于 2020-01-11 11:28:47

问题


I have spent almost the whole day trying to find a solution to this problem.

I have successfully written code to dynamically retrieve and display the whole lot of fonts using the Google fonts API and jQuery 1.4.4. (works in all browsers)

I have had to change jQuery to version 1.7.2 and unfortunately noticed that the code I wrote works well in all browsers except for Internet Explorer.

I did some testing and found that in Internet Explorer $.getJSON or $.ajax fail to load the JSON font data from Google when using jQuery versions higher than 1.4.4.

This is the code I am using:

$(function(){           

$.getJSON('https://www.googleapis.com/webfonts/v1/webfonts?key=XXXXXX', function(json) {

alert(json);

});
});

After some research I have tried this too:

$.ajax({
type: "get",
url: "https://www.googleapis.com/webfonts/v1/webfonts?key=XXXXXXXX",
cache:false,
dataType:'json',
success: function(data){
alert(data);
}
});

Both methods fail in Internet Explorer using any jQuery version greater than 1.4.4 - nothing happens.

Any ideas why? Thanks for the help.


回答1:


It seems to be IE that is blocking connection to hosts outside of your site's domain. This is due to the Same Origin Policy. This is usually not a big deal with the latest and greatest browsers out there, although it can still occur with any browser. I tested your code using JSFiddle and it threw an error about same origin in Chrome 21.

Normally, the way to fix this is to use JSONP. Unfortunately, the Google Webfonts API does not support JSONP. The best way that I can think about getting that data cross-browser is to download the JSON using a server-side programming language such as PHP. From there, you can echo the JSON out to the page and use the $.getJSON function to grab that data locally on your server.

EXAMPLE: fontApi.php (local file on your server)

<?php
$json = file_get_contents('https://www.googleapis.com/webfonts/v1/webfonts?key=XXXXXX');
die($json); // prints JSON to the screen that jQuery can use
?>

Then use the following jQuery...

$.getJSON('fontApi.php', function(json) {
    //your code
});

Hopefully this helps you out :)



来源:https://stackoverflow.com/questions/11874617/getjson-and-google-fonts-api-stops-working-in-internet-explorer-with-jquery-ve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!