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

StackOverflow https://stackoverflow.com/questions/11874617

سؤال

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.

هل كانت مفيدة؟

المحلول

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 :)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top