Reputation: 21126
( function( $ ) {
function CleanQueryString( query )
{
return encodeURI( query );
};
function ConcatData( settings )
{
settings.concatUrl = settings.googleUrl;
settings.concatUrl = settings.concatUrl.replace( "{key}", settings.googleApiKey );
settings.concatUrl = settings.concatUrl.replace( "{country}", settings.country );
settings.concatUrl = settings.concatUrl.replace( "{query}", settings.cleanQuery );
};
$.fn.GoogleSearchResult = function( options ) {
var settings = $.extend( {
query: null,
googleApiKey: "myapikey",
googleUrl: "https://www.googleapis.com/shopping/search/v1/public/products?key={key}&country={country}&q={query}&alt=json",
concatUrl: "",
country: "UK",
cleanQuery: ""
}, options);
return this.each( function() {
if( settings.query )
{
var $t = $(this);
settings.cleanQuery = CleanQueryString( settings.query );
ConcatData( settings );
alert( settings.concatUrl ); // This alerts the correct url and I've checked that it returns json
$.getJSON( settings.concatUrl, function( data ) {
alert("hi"); // This never alerts
$t.html( data );
});
}
return false;
} );
};
} )( jQuery );
I can't get my $.getJSON to work.. any ideas why that might not be returning anything:
https://developers.google.com/shopping-search/v1/getting_started
The url I send returns the correct data when I go straight to it.
Upvotes: 2
Views: 215
Reputation: 18233
You need to use JSONP to transfer data from an external source. The Google API supports this, so in terms of your code, this is as simple as appending &callback=xyz
to your url, where xyz
is some function that the external server will wrap your code in.
https://www.googleapis.com/shopping/search/v1/public/products?key={key}&country={country}&q={query}&alt=json&callback=xyz
jQuery automatically looks for a callback named ?
, so you can either use callback=?
or specify a custom name by adding jsonp: xyz
to your AJAX request params.
Upvotes: 0
Reputation: 21126
jQuery.support.cors = true;
$.getJSON( settings.concatUrl, function( data ) {
alert(data);
$t.html( data );
}).error(function(xhr, status, error) { alert("error" + status +" " + error); }) ;
Jquery cross domain support can be enabled with this setting.
Upvotes: 0
Reputation: 92893
Are you attempting to access JSON on a different server? If so, you need to load it on your own server using some kind of server-side script, and access that using .getJSON
. Google Shopping Search doesn't appear to offer JSON-P.
If you can write a PHP page or some other server-side language, it's trivial to get and return the external JSON, which will now be on your own server and can be easily loaded using .getJSON
.
Upvotes: 1